Accessing member variables of another object of the same class in Ruby

In Java, I can do:

public boolean equals(Object other) {
    return this.aPrivateVariable == ((MyClass)other).aPrivateVariable;
}

This allows me to define equality without breaking the encapsulation of my class. How can I do the same in Ruby?

Thanks.

+3
source share
3 answers

In Ruby, variable instances, as well as private methods, are available only for the object itself, and not for any other object, regardless of their class. Protected methods are accessible to the object itself and to other objects of the same class.

So, to do what you want, you can define a protected getter method for your variable.

Edit: Example:

class Foo
  protected
  attr_accessor :my_variable # Allows other objects of same class
                             # to get and set the variable. If you
                             # only want to allow getting, change
                             # "accessor" to "reader"

  public
  def ==(other)
    self.my_variable == other.my_variable
  end
end
+4
source

Just do a non-cast comparison that is not needed in Ruby.

class C1
  attr_accessor :property

  def == other
    property == other.property
  end
end

class C2
  attr_accessor :property

  def == other
    property == other.property
  end
end

c1 = C1.new
c1.property = :foo

c2 = C2.new
c2.property = :bar

p c1 == c2 # => false

c1.property = :bar
p c1 == c2 # => true

: equals? ==.

-1

As others pointed out, you need to override #==in your class. However, one of them is hash tables. If you want two different instances of your class with o1 == o2 #=> truea hash to be equal to the same value in the hash table, you need to override #hashand #eql?let the hash table know that they represent the same value.

class Foo
  def initialize(x,y,z)
    @x,@y,@z = x,y,z
  end
  def ==(other)
    @y == other.instance_eval { @y }
  end
end

o1 = Foo.new(0, :frog, 2)
o2 = Foo.new(1, :frog, 3)

o1 == o2 #=> true

h1 = Hash.new
h1[o1] = :jump
h1[o2] #=> nil

class Foo
  def hash
    @y.hash
  end
  def eql?(other)
    self == other
  end
end

h2 = Hash.new
h2[o1] = :jump_again
h2[o2] #=> :jump_again
-1
source

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


All Articles