Search code examples
rubysavonfunction

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


Solution

  • 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.