Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The ruby def << syntax for defining methods

Im trying to work my way through the Savon gem's source code and I found this line..

def initialize
  @documents = []
end

def <<(document)
  @documents << document
end

I was curious as to what the def << method does. And why he might have elected to use that syntax over something (maybe) more conventional.

the source code can be found at: https://github.com/savonrb/savon/blob/master/lib/savon/wsdl/document_collection.rb

like image 801
Davey Avatar asked Nov 30 '13 04:11

Davey


2 Answers

def << literally creates a new method called <<. Looking at the Ruby Operator Expressions reference, you can see a handful of those are methods that can be implemented, overridden, etc.

Nothing "unconventional" or special about it, just kind of weird if you're used to languages where that's handled in a special way.

like image 172
Nick Veys Avatar answered Sep 20 '22 20:09

Nick Veys


<< in Ruby is used to add an element, e.g. pushing into an array

[1,2,3] << 4
 => [1, 2, 3, 4]

by defining << you can use this nice syntax in your class to push in arbitrary objects like this:

my_custom_class << object
like image 30
Simon Duncombe Avatar answered Sep 21 '22 20:09

Simon Duncombe