Merge and interleave two arrays in Ruby

后端 未结 11 2145
猫巷女王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"]
    

提交回复
热议问题