Merge arrays in Ruby/Rails

57,430

Solution 1

Like this?

⚡️ irb
2.2.2 :001 > [1,2,3] + [4,5,6]
 => [1, 2, 3, 4, 5, 6] 

But you don't have 2 arrays.

You could do something like:

@movie = Movie.first()
@options = Movie.order("RANDOM()").first(3).to_a << @movie

Solution 2

There's two parts to this question:

  1. How to "merge two arrays"? Just use the + method:

    [1,2,3] + [2,3,4]
    => [1, 2, 3, 2, 3, 4]
    
  2. How to do what you want? (Which as it turns out, isn't merging two arrays.) Let's first break down that problem:

    @movie is an instance of your Movie model, which you can verify with @movie.class.name.

    @options is an Array, which you can verify with @options.class.name.

    All you need to know now is how to append a new item to an array (i.e., append your @movie item to your @options array)

    You do that using the double shovel:

    @options << @movie
    

    this is essentially the same as something like:

    [1,2,3] << 4
    => [1,2,3,4]
    

Solution 3

To merge (make the union of) arrays:

[1, 2, 3].union([2, 4, 6]) #=> [1, 2, 3, 4, 6] (FROM RUBY 2.6)
[1, 2, 3] | [2, 4, 6] #=> [1, 2, 3, 4, 6]

To concat arrays:

[1, 2, 3].concat([2, 4, 6]) #=> [1, 2, 3, 2, 4, 6] (FROM RUBY 2.6)
[1, 2, 3] + [2, 4, 6] #=> [1, 2, 3, 2, 4, 6]

To add element to an array:

[1, 2, 3] << 4 #=> [1, 2, 3, 4]

But it seems that you don't have arrays, but active records. You could convert it to array with to_a, but you can also do directly:

Movie.order("RANDOM()").first(3) + [@movie]

which returns the array you want.

Solution 4

@movie isn't an array in your example, it is just a single instance of a movie. This should solve your problem:

@options << @movie

Solution 5

Well, If you have an element to merge in an array you can use <<:

Eg: array = ["a", "b", "c"],  element = "d"
array << element 
=> ["a", "b", "c", "d"]

Or if you have two arrays and want duplicates then make use of += or simply + based on your requirements on mutability requirements:

Eg: array_1 = [1, 2], array_2 = [2, 3]
array_1 += array_2
=> [1, 2, 2, 3]

Or if you have two arrays and want to neglect duplicates then make use of |= or simply |:

Eg: array_1 = [1, 2], array_2 = [2, 3]
array_1 |= array_2
=> [1, 2, 3] 
Share:
57,430

Related videos on Youtube

Croaton
Author by

Croaton

Updated on April 09, 2020

Comments

  • Croaton
    Croaton about 4 years

    How can I merge two arrays? Something like this:

    @movie = Movie.first()
    @options = Movie.order("RANDOM()").first(3).merge(@movie)
    

    But it doesn't work.

    In @options I need an array with four elements includes @movie.

  • Croaton
    Croaton about 9 years
    Rather [1, 2, 3] + [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
  • Croaton
    Croaton about 9 years
    Thanks! I always forget about "<<" :)