4

Came across this code.

def setup(&block)
  @setups << block
end

What does this line do?

@setups << block

Interested in what the does "<<".

The manual says that it is the operator of double shift, but he is here with?

sawa
  • 160,959
  • 41
  • 265
  • 366
user1466717
  • 779
  • 1
  • 10
  • 21

3 Answers3

8

For an array << is the append method. It adds an item to the end of the array.

So in your specific case when you call setup with a block the Proc object made from the block is stored in @setups.

Note: as sbeam points out in his comment, because << is a method, it can do different things depending on the type of object it is called on e.g. concatenation on strings, bit shifting on integers etc.

See the "ary << obj → ary" documentation.

Community
  • 1
  • 1
mikej
  • 63,686
  • 16
  • 149
  • 130
  • it actually is not an operator, it's just a funny name for a method. You are calling the `< – sbeam Dec 18 '12 at 04:11
  • @sbeam yes, you're right. I was oversimplifying a bit in the answer and agree that it is an important distinction to understand within Ruby. Will update the answer to improve it a bit. – mikej Dec 18 '12 at 12:51
1

It's building an array by pushing elements onto the end of it.

Here's the manual entry.

Brian Agnew
  • 261,477
  • 36
  • 323
  • 432
1

<< in Ruby is commonly used to mean append - add to a list or concatenate to a string.

The reason Ruby uses this is unclear but may be because the library largely distinguishes between changing an object and returning a changed object (methods that change the objects tend to have a ! suffix). In this way, << is the change-the-object counterpart to +.

Jesper
  • 7,193
  • 4
  • 40
  • 55