== 是 Ruby 中的特殊方法吗?
我知道 Ruby 中的 x == y
解释为 a.==(y)
。我尝试检查是否可以使用自定义方法 foo
实现相同的效果,如下所示:
class Object
def foo(n)
self == n
end
end
class A
attr_accessor :x
end
a = A.new
a.x = 4
puts a.x.==(4) # => true
puts a.x.foo(4) # => true
puts a.x == 4 # => true
puts a.x foo 4 # => in `x': wrong number of arguments (1 for 0) (ArgumentError)
不幸的是,这不起作用。我缺少什么? ==
是 Ruby 中的特殊方法吗?
I understand that x == y
in Ruby interpreted as a.==(y)
. I tried to check if I can achieve the same with custom method, foo
, like this:
class Object
def foo(n)
self == n
end
end
class A
attr_accessor :x
end
a = A.new
a.x = 4
puts a.x.==(4) # => true
puts a.x.foo(4) # => true
puts a.x == 4 # => true
puts a.x foo 4 # => in `x': wrong number of arguments (1 for 0) (ArgumentError)
Unfortunately, this doesn't work. What am I missing ? Is ==
a special method in Ruby ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,
==
不是 Ruby 中的特殊方法。这是一种与其他方法一样的方法。您所看到的只是一个解析问题:与 IOW相同
,您将
foo(4)
作为参数传递给x
,但是x 不接受任何参数。
然而,有一种特殊的运算符语法,它允许您
编写代替
为有限的运算符列表
:此外,还有一种特殊的语法允许您
编写
代替以及
以及
代替
和
和
然后
,还有
和
代替
和
最后但并非最不重要的
代替
No,
==
is not a special method in Ruby. It's a method like any other. What you are seeing is simply a parsing issue:is the same as
IOW, you are passing
foo(4)
as an argument tox
, butx
doesn't take any arguments.There is, however, special operator syntax, which allows you to write
instead of
for a limited list of operators:
Also, there is special syntax that allows you to write
and
instead of
and
As well as
and
instead of
and
Then, there is
and
instead of
and
and last but not least
instead of
作为运算符的方法在 Ruby 中会被特殊对待,至少在语法方面是这样。该语言不像 Haskell 那样灵活,在 Haskell 中,您可以通过将任何函数的名称括在反引号中将其转换为中缀运算符:中缀运算符的列表是预先确定的。
自定义中缀会出现的问题之一是运算符优先级和结合性的处理:例如,解析器如何处理如下语句:
Methods that are operators are treated specially in Ruby, at least syntax-wise. The language is not as flexible as, say, in Haskell where you can turn any function into an infix operator by enclosing its name in backticks: the list on infix operators are pre-determined.
One of the problems that would arise from custom infixes is the handling of operator precedence and associativity: for eaxmple, how would the parser handle a statement like: