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
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.
<< 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With