32

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
  • 1,812
  • 3
  • 18
  • 28

5 Answers5

58

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
Nick Veys
  • 23,458
  • 4
  • 47
  • 64
12

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.

11

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]
    
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
joshua.paling
  • 13,762
  • 4
  • 45
  • 60
3

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

@options << @movie
spickermann
  • 100,941
  • 9
  • 101
  • 131
3

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] 
Hexfire
  • 5,945
  • 8
  • 32
  • 42
Ayman Hussain
  • 255
  • 2
  • 2