Ruby 操作符方法调用与普通方法调用 [英] Ruby operator method calls vs. normal method calls

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

问题描述

我想知道为什么调用操作符方法不需要点?或者更确切地说,为什么不能在没有点的情况下调用普通方法?

示例<前>Foo类def +(对象)把这会起作用"结尾定义加(对象)把这不会"结尾结尾f = Foo.newf + "anything" # "这行得通"f plus "anything" # NoMethodError: undefined method `plus' for main:Object

解决方案

该实现不具有允许新运算符的泛型定义所需的额外复杂性.

相反,Ruby 有一个 Yacc 解析器,它使用静态定义的语法.你得到了内置的运算符,就是这样.符号出现在语法中的一组固定句子中.正如您所指出的,运算符可以被重载,这比大多数语言提供的要多.

当然不是因为 Matz 懒惰.

Ruby 实际上有一个极其复杂的语法,大致达到了 Yacc 所能完成的极限.要想变得更复杂,就需要使用可移植性较差的编译器生成器,或者需要用 C 手动编写解析器,而这样做会限制未来以自己的方式实现的可移植性,并且不提供Yacc 输入的世界.这将是一个问题,因为 Ruby 的 Yacc 源代码是唯一的 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?

Example

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.

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

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

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