2

Assume that we have a class

class Foo
  def +   (element); end
  def add (element); end
end

Now we can invoke these two methods like:

foo = Foo.new
foo.+('bar')
foo.add('bar')

And that's resonable. This is the right way of invoking methods.

My question is: Why we can do something like:

foo + 'bar'

but not:

foo add 'bar'

Does Ruby distinguish if method name is actually operator overloading? How does it work?

Kamil Lelonek
  • 14,592
  • 14
  • 66
  • 90
  • Not a bad question! +1 – Arup Rakshit Jan 26 '14 at 20:09
  • 1
    Ruby distinguishes strings that represent operators from other strings. So when you do `def +` it knows you are defining (or overloading) an existing operator. Since `add` isn't already an operator, it's treated as a normal method. You can define a custom operator using a gem, such as described here: http://stackoverflow.com/questions/11874579/define-custom-ruby-operator – lurker Jan 26 '14 at 20:13
  • mbratch, I want to accept your question! – Kamil Lelonek Jan 26 '14 at 20:36

2 Answers2

0

This is one of the things many people refer to as Ruby's syntax sugar. The language recognizes these mathematical operators as well as other ASCII symbol operators, such as the << insertion operator, and allows them to be called with white space and without the method dot. This allows for a more natural usage of the method.

Your #add method is not recognized by Ruby to be a standard operator and so this syntax help is not performed.

rafroehlich2
  • 1,308
  • 12
  • 16
0

Ruby treats specific method names called also as a (subset of) operators differently. They can be invoked without a dot ., can be prepended to an owning object (do not require an argument, ie. unary operators) and have different precedence order then standard methods.

Here is a fixed list of concrete `operator' methods which are not keywords and can be defined or overloaded (marked with Y).

David Unric
  • 7,421
  • 1
  • 37
  • 65