Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在Ruby中访问同一类的其他对象的成员变量_Java_Ruby_Equals - Fatal编程技术网

Java 在Ruby中访问同一类的其他对象的成员变量

Java 在Ruby中访问同一类的其他对象的成员变量,java,ruby,equals,Java,Ruby,Equals,在Java中,我可以做到: public boolean equals(Object other) { return this.aPrivateVariable == ((MyClass)other).aPrivateVariable; } 这允许我在不破坏类封装的情况下定义相等。 我如何在Ruby中实现同样的功能 谢谢。在ruby中,实例变量和私有方法只能由对象本身访问,而不能由任何其他对象访问,无论它们是什么类。受保护的方法可用于对象本身和同一类的其他对象 因此,要想做您想做的事情

在Java中,我可以做到:

public boolean equals(Object other) {
    return this.aPrivateVariable == ((MyClass)other).aPrivateVariable;
}
这允许我在不破坏类封装的情况下定义相等。 我如何在Ruby中实现同样的功能


谢谢。

在ruby中,实例变量和私有方法只能由对象本身访问,而不能由任何其他对象访问,无论它们是什么类。受保护的方法可用于对象本身和同一类的其他对象

因此,要想做您想做的事情,您可以为您的变量定义一个受保护的getter方法

编辑:例如:

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

只需在没有强制转换的情况下进行比较,这在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?
更改为
=

正如其他人指出的那样,您需要在课堂上重新定义
#==
。不过,有一个问题是哈希表。如果希望类的两个不同实例的
o1==o2#=>true
散列到哈希表中的相同值,则需要重新定义
#散列
#eql?
,以便哈希表知道它们代表相同的值

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

你知道代码是不安全的吗?不能保证强制转换会起作用,在这种情况下,你会得到一个ClassCastException和aPrivateVariable,最好也是一个原语。这两个点都是有效的——但既然问题是关于访问控制,我们当然可以让它们滑动。(和
aPrivateVariable
也可以是枚举或单例,并通过“==”进行有效比较)是的,我知道你提到的一点。我只是写了最小值来说明问题。不过还是要感谢:)我很确定他不希望这个变量是可读的或是从外部设置的(不包括反射,反射总是有效的),这就是为什么他称他的变量为“aPrivateVariable”。另外:不要覆盖
equals?
,它会破坏东西。覆盖
==
。关于相等,你是对的吗?vs.==。访问器仅用于演示。OP可以很容易地更改该部分。确切地说,我不希望从外部访问该变量。我将进行检查,但这看起来像是我的答案:)