In ruby, operators are in fact method calls. If you have two variables a
and b
and want to check their equality, you generally write a == b
, but you could write a.==(b)
. The last syntax shows what happens during an equality check : ruby calls a
's method ==
and passes it b
as an argument.
You can implement custom equality check in your classes by defining the ==
and/or the eql?
methods. In your example, other
is simply the name of the argument it receives.
class Person
attr_accessor :name
def initialize name
@name = name
end
end
a = Person.new("John")
b = Person.new("John")
a == b # --> false
class Person
def == other
name == other.name
end
end
a == b # --> true
For your second question, the only methods starting with ==
you're allowed to implement are ==
and ===
. Check here for the full list of restrictions on method names in ruby: What are the restrictions for method names in Ruby?