Is == special method in Ruby?

I understand that x == y in Ruby is interpreted as a.==(y) . I tried to check if I can do the same with a custom method, foo , for example:

 class Object def foo(n) self == n end end class A attr_accessor :x end a = A.new ax = 4 puts ax==(4) # => true puts axfoo(4) # => true puts ax == 4 # => true puts ax foo 4 # => in `x': wrong number of arguments (1 for 0) (ArgumentError) 

Unfortunately this does not work. What am I missing? Is == special method in Ruby?

+6
source share
2 answers

No, == not a special method in Ruby. This is a method like any other. What you see is just a parsing issue:

 ax foo 4 

coincides with

 ax(foo(4)) 

IOW, you pass foo(4) as an argument to x , but x does not accept any arguments.

There is, however, a special operator syntax that allows you to write

 a == b 

instead

 a.== b 

for a limited list of operators:

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

In addition, there is a special syntax that allows you to write

 !a 

and

 ~a 

instead

 a.! 

and

 a.~ 

Like

 +a 

and

 -a 

instead

 a.+@ 

and

 a.-@ 

Then there is

 a[b] 

and

 a[b] = c 

instead

 a.[] b 

and

 a.[]= b, c 

and finally no less

 a.(b) 

instead

 a.call b 
+15
source

Methods that are statements are handled specifically in Ruby, at least syntactically. The language is not as flexible as, say, in Haskell, where you can turn any function into an infix operator by including its name in backlinks: a predefined list for infix operators.

One of the problems that can occur in user infixes is the processing of priorities and associativity of operators: for eaxmple, it would be like a parser processing an operator like:

 a foo b == c # should this be (a foo b) == c or a foo (b == c) 
+2
source

Source: https://habr.com/ru/post/892385/


All Articles