Reputation: 1812
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
.
Upvotes: 32
Views: 77400
Reputation: 3793
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.
Upvotes: 16
Reputation: 285
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]
Upvotes: 4
Reputation: 13952
There's two parts to this question:
How to "merge two arrays"? Just use the +
method:
[1,2,3] + [2,3,4]
=> [1, 2, 3, 2, 3, 4]
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]
Upvotes: 11
Reputation: 106802
@movie
isn't an array in your example, it is just a single instance of a movie. This should solve your problem:
@options << @movie
Upvotes: 3
Reputation: 23939
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
Upvotes: 59