Reputation: 789
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?
Upvotes: 4
Views: 666
Reputation: 66263
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.
Upvotes: 8
Reputation: 7605
<<
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 +
.
Upvotes: 1
Reputation: 272237
It's building an array by pushing elements onto the end of it.
Here's the manual entry.
Upvotes: 1