Merge arrays in Ruby/Rails

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.


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]
    

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