Ruby operator method calls vs. normal method calls

后端 未结 5 630
既然无缘
既然无缘 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:08

    Because Ruby has "syntax sugar" that allows for a variety of convenient syntax for preset situations. For example:

    class Foo
      def bar=( o ); end
    end
    
    # This is actually calling the bar= method with a parameter, not assigning a value
    Foo.new.bar = 42
    

    Here's a list of the operator expressions that may be implemented as methods in Ruby.

提交回复
热议问题