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,765
  • 1
  • 25
  • 32
  • Sure, i know what is an array. – datalost Sep 21 '11 at 01:38
  • So you know that `[search] << AnotherClass.new` is equivalent to `item = AnotherClass.new; current_array = [search]; current_array.<<(item)`, and that the last command calls Array#<<, right? – Andrew Grimm Sep 21 '11 at 02:20

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
  • 52,489
  • 13
  • 125
  • 145
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
  • 64,083
  • 21
  • 152
  • 198