开发者

Is == a special method in Ruby?

I understand that x == y in Ruby interpreted as a.==(y). I tried to check if 开发者_如何学CI 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 ?


No, == is not a special method in Ruby. It's a method like any other. What you are seeing is simply a parsing issue:

a.x foo 4

is the same as

a.x(foo(4))

IOW, you are passing foo(4) as an argument to x, but x doesn't take any arguments.

There is, however, special operator syntax, which allows you to write

a == b

instead of

a.== b

for a limited list of operators:

==
!=
<
>
<=
>=
<=>
===
&
|
*
/
+
-
%
**
>>
<<
!==
=~
!~

Also, there is special syntax that allows you to write

!a

and

~a

instead of

a.!

and

a.~

As well as

+a

and

-a

instead of

a.+@

and

a.-@

Then, there is

a[b]

and

a[b] = c

instead of

a.[] b

and

a.[]= b, c

and last but not least

a.(b)

instead of

a.call b


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:

a foo b == c # should this be (a foo b) == c or a foo (b == c)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜