Ruby operator method calls vs. normal method calls

后端 未结 5 609
既然无缘
既然无缘 2020-12-15 23:52

I\'m wondering why calls to operator methods don\'t require a dot? Or rather, why can\'t normal methods be called without a dot?

Example

class Foo
  def +(obje         


        
5条回答
  •  伪装坚强ぢ
    2020-12-16 00:18

    The implementation doesn't have the additional complexity that would be needed to allow generic definition of new operators.

    Instead, Ruby has a Yacc parser that uses a statically defined grammar. You get the built-in operators and that's it. Symbols occur in a fixed set of sentences in the grammar. As you have noted, the operators can be overloaded, which is more than most languages offer.

    Certainly it's not because Matz was lazy.

    Ruby actually has a fiendishly complex grammar that is roughly at the limit of what can be accomplished in Yacc. To get more complex would require using a less portable compiler generator or it would have required writing the parser by hand in C, and doing that would have limited future implementation portability in its own way as well as not providing the world with the Yacc input. That would be a problem because Ruby's Yacc source code is the only Ruby grammar documentation and is therefore "the standard".

提交回复
热议问题