2

I'm working with a legacy Rails project and found a piece of code that don't understand.

Given that

 search = Sunspot.search(entities)
 ...
 [search] << AnotherClass.new 

Obviously they are two different object type. What is the meaning of using [] <<

datalost
  • 3,595
  • 1
  • 24
  • 32

2 Answers2

4

[...] is an Array literal, and << is an operator on Array that means "append". It returns a new array with right-hand-element appended to the end. So:

[search] << AnotherClass.new  #  =>  [search, AnotherClass.new]
Ben Lee
  • 51,343
  • 12
  • 121
  • 144
3

The << operator appends the object on the right to the array.

[search] << AnotherClass.new 

Try this on the Rails console:

a = [1,2]
=> [1, 2]
>> a << 3  # appends 3 to the array
=> [1, 2, 3]

>> [6, 7] << 8  # appends 8 to the newly declared array on the left
=> [6, 7, 8]
Harish Shetty
  • 63,225
  • 21
  • 147
  • 197