Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is == a special method in 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 ?

like image 303
Misha Moroshko Avatar asked Jul 09 '11 10:07

Misha Moroshko


1 Answers

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
like image 66
Jörg W Mittag Avatar answered Nov 15 '22 07:11

Jörg W Mittag