Merge and interleave two arrays in Ruby

后端 未结 11 2101
猫巷女王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:00

    How about a more general solution that works even if the first array isn't the longest and accepts any number of arrays?

    a = [
        ["and", "&"],
        ["Cat", "Dog", "Mouse"]
    ]
    
    b = a.max_by(&:length)
    a -= [b]
    b.zip(*a).flatten.compact
    
     => ["Cat", "and", "Dog", "&", "Mouse"]
    

提交回复
热议问题