33

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.

5 Answers 5

61

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
Sign up to request clarification or add additional context in comments.

2 Comments

Rather [1, 2, 3] + [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
Thanks! I always forget about "<<" :)
16

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.

Comments

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]
    

Comments

4

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] 

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.