« Back to Index

In Ruby using the << operator as a method identifier has special meaning. It allows us to call the method without using a period (so we can do foo << "abc" and not have to do foo.<< "abc")

View original Gist on GitHub

<< method.rb

class Foo
  def <<(something)
    puts something
  end

  def say(something)
    puts something
  end
end

foo = Foo.new

foo.<<("hi") # => hi
foo.<< "hi"  # => hi
foo << "hi"  # => hi

foo.say("hi") # => hi
foo.say "hi"  # => hi
foo say "hi"  # => NoMethodError: undefined method `say' for main:Object