Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "other" object and how does it work?

Tags:

ruby

I have seen other used often in class comparisons, such as

def ==(other)
  ...
end

or

def eql?(other)
  self == other
end

but I still have found no explanation of what it actually is. What's going on here?

And perhaps this is for another question, but what does starting a method with == imply?

like image 383
lusk Avatar asked Mar 09 '26 05:03

lusk


2 Answers

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?

like image 196
VonD Avatar answered Mar 11 '26 19:03

VonD


other is a parameter to this method, the object, that is being passed.

For example:

class A
  def ==(other)
    :lala == other
  end
end

obj = A.new
obj.==(:foo) # full syntax, just like any other method
# but there's also a shorthand for operators:
obj == :foo  # => false
obj == :lala # => true
like image 23
Vasfed Avatar answered Mar 11 '26 20:03

Vasfed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!