Merge and interleave two arrays in Ruby

后端 未结 11 1978
猫巷女王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"]
    
    0 讨论(0)
  • 2020-12-04 08:01

    If you don't want duplicate, why not just use the union operator :

    new_array = a | s
    
    0 讨论(0)
  • 2020-12-04 08:03

    You can do that with:

    a.zip(s).flatten.compact
    
    0 讨论(0)
  • 2020-12-04 08:03

    One way to do the interleave and also guarantee which one is the biggest array for the zip method, is to fill up one of the arrays with nil until the other array size. This way, you also guarantee which element of which array will be on first position:

    preferred_arr = ["Cat", "Dog", "Mouse"]
    other_arr = ["and","&","are","great","friends"]
    
    preferred_arr << nil while preferred_arr.length < other_arr.length
    preferred_arr.zip(other_arr).flatten.compact
    #=> ["Cat", "and", "Dog", "&", "Mouse", "are", "great", "friends"]
    
    0 讨论(0)
  • 2020-12-04 08:05
    arr = [0, 1]
    arr + [2, 3, 4]
    
    //outputs [0, 1, 2, 3, 4]
    
    0 讨论(0)
  • 2020-12-04 08:07

    This won't give a result array in the order Chris asked for, but if the order of the resulting array doesn't matter, you can just use a |= b. If you don't want to mutate a, you can write a | b and assign the result to a variable.

    See the set union documentation for the Array class at http://www.ruby-doc.org/core/classes/Array.html#M000275.

    This answer assumes that you don't want duplicate array elements. If you want to allow duplicate elements in your final array, a += b should do the trick. Again, if you don't want to mutate a, use a + b and assign the result to a variable.

    In response to some of the comments on this page, these two solutions will work with arrays of any size.

    0 讨论(0)
提交回复
热议问题