Search code examples
rubyoperatorsmetaprogrammingmonkeypatching

Can Ruby operators be aliased?


I'm interested in how one would go in getting this to work :

me = "this is a string"
class << me
  alias :old<< :<<
  def <<(text)
    old<<(text)
    puts "appended #{text}"
  end
end

I'd like that when something gets appended to the me variable, the object will use the redefined method.

If I try to run this, I get syntax error, unexpected ':', expecting kEND at :<<.


Solution

  • :old<< looks like ":old <<". Try just :old, or if you really want, :"old<<" (but have fun calling it through that name).