Ruby运算符方法调用与常规方法调用 [英] Ruby operator method calls vs. normal method calls

查看:54
本文介绍了Ruby运算符方法调用与常规方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么对运算符方法的调用不需要点吗?或者,为什么不能在没有点的情况下调用普通方法?

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?

示例


class Foo
  def +(object)
    puts "this will work"
  end
  def plus(object)
    puts "this won't"
  end
end 
f = Foo.new
f + "anything" # "this will work"
f plus "anything" # NoMethodError: undefined method `plus' for main:Object

推荐答案

该实现没有允许通用定义新运算符所需的额外复杂性.

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

相反,Ruby有一个Yacc解析器,该解析器使用静态定义的语法.您可以获得内置的运算符,仅此而已.符号出现在语法中固定的一组句子中.您已经注意到,运算符 可以重载,这比大多数语言所提供的更多.

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.

当然不是因为Matz懒.

Certainly it's not because Matz was lazy.

Ruby实际上有一个非常复杂的语法,大约只能在Yacc中完成.要变得更加复杂,可能需要使用移植性较小的编译器生成器,或者需要使用C手动编写解析器,并且 将以其自己的方式限制将来的实现可移植性,并且不提供Yacc输入的世界.这将是一个问题,因为Ruby的Yacc源代码是唯一的Ruby语法文档,因此是标准".

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".

这篇关于Ruby运算符方法调用与常规方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆