Merge arrays in Ruby/Rails

Croaton picture Croaton · Apr 30, 2015 · Viewed 42.5k times · Source

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.

Answer

Nick Veys picture Nick Veys · Apr 30, 2015

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