Merge and interleave two arrays in Ruby

后端 未结 11 1979
猫巷女王i
猫巷女王i 2020-12-04 07:34

I have the following code:

a = [\"Cat\", \"Dog\", \"Mouse\"]
s = [\"and\", \"&\"]

I want to merge the array s into array <

相关标签:
11条回答
  • 2020-12-04 08:09

    Interleave 2D array of any size

    arr = [["Cat", "Dog", "Mouse"],
     ["and", "&"],
     ["hello", "there", "you", "boo", "zoo"]]
    
    max_count = arr.map(&:count).max
    max_count.times.map{|i| arr.map{|a| a[i]}}.flatten.compact
    
    #=> ["Cat", "and", "hello", "Dog", "&", "there", "Mouse", "you", "boo", "zoo"]
    
    0 讨论(0)
  • 2020-12-04 08:11
    s.inject(a, :<<)
    
    s   #=> ["and", "&"]
    a   #=> ["Cat", "Dog", "Mouse", "and", "&"]
    

    It doesn't give you the order you asked for, but it's a nice way of merging two arrays by appending to the one.

    0 讨论(0)
  • 2020-12-04 08:14

    It's not exactly elegant, but it works for arrays of any size:

    >> a.map.with_index { |x, i| [x, i == a.size - 2 ? s.last : s.first] }.flatten[0..-2] 
    #=> ["Cat", "and", "Dog", "&", "Mouse"]
    
    0 讨论(0)
  • 2020-12-04 08:17

    Here's a solution that allows interleaving multiple arrays of different sizes (general solution):

    arr = [["Cat", "Dog", "Mouse", "boo", "zoo"],
     ["and", "&"],
     ["hello", "there", "you"]]
    
    first, *rest = *arr; first.zip(*rest).flatten.compact
    => ["Cat", "and", "hello", "Dog", "&", "there", "Mouse", "you", "boo", "zoo"]
    
    0 讨论(0)
  • 2020-12-04 08:17

    To handle the situation where both a & s are not of the same size:

    a.zip(s).flatten.compact | s
    
    • .compact will remove nil when a is larger than s
    • | s will add the remaining items from s when a is smaller than s
    0 讨论(0)
提交回复
热议问题