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 ?
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, butxdoesn’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