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
  • 165,429
  • 45
  • 277
  • 381
user1466717
  • 779
  • 1
  • 10
  • 23

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
  • 65,295
  • 17
  • 152
  • 131
  • it actually is not an operator, it's just a funny name for a method. You are calling the `<<` method on the object, which in the case of an Array is equivalent to `push` and for a String is equivalent to `+`. `<<` is also referred to as the "Bitwise Shift Left operator", but this actually means when you call `<<` on an Integer, it performs a leftwards bit shift. I'm being pedantic, but it's kinda important to understand in Ruby, since they can be redefined and change in function based on the receiving object. – 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
  • 268,207
  • 37
  • 334
  • 440
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,477
  • 4
  • 40
  • 57