Ruby 实例的唯一性
如果我分别创建两个具有相同内容的 String 实例,它们是相同的。默认情况下,自定义类的情况并非如此(请参见下面的示例)。
如果我有自己的类(下面的Test
)并且我有一个唯一的变量(下面的@v
),即。具有相同 @v
的两个 Test
实例应该被视为相同,那么我将如何告诉 Ruby 这是这种情况呢?
考虑这个例子:
class Test
def initialize(v)
@v = v
end
end
a = {Test.new('a') => 1, Test.new('b') => 2}
a.delete(Test.new('a'))
p a
# # Desired output:
# => {#<Test:0x100124ef8 @v="b">=>2}
If I create two String instances with the same content separately they are identical. This is not the case with custom classes by default (see example below).
If I have my own class (Test
below) and I have a variable (@v
below) which is unique, ie. two Test
instances with the same @v
should be treated as identical, then how would I go about telling Ruby this is the case?
Consider this example:
class Test
def initialize(v)
@v = v
end
end
a = {Test.new('a') => 1, Test.new('b') => 2}
a.delete(Test.new('a'))
p a
# # Desired output:
# => {#<Test:0x100124ef8 @v="b">=>2}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要定义一个
==
方法来定义相等对您的类意味着什么。在这种情况下,您需要:You need to define an
==
method that defines what equality means for your class. In this case, you would want:您正在使用
Test
类的对象作为哈希的键。为了使其正常运行(以及a.delete
),您需要在 Test 中定义两个方法:Test#hash
和Test#eql?< /code>
来自: http://ruby-doc.org/core/classes/Hash .html
You are using objects of class
Test
as keys for the hash. In order for that to function properly (and consequentlya.delete
), you need to define two methods inside Test:Test#hash
andTest#eql?
From: http://ruby-doc.org/core/classes/Hash.html
我找到了一种不同的方法来解决这个问题,通过在内部跟踪 Test 的所有实例,我可以返回预制实例,而不是创建一个新实例并告诉 ruby 它们是等效的:
现在
Test.new('a' ) == Test.new('a')
和Test.new('a') === Test.new('a')
: )I found a different way to tackle this, by keeping track of all the instances of Test internally I can return the premade instance rather than making a new one and telling ruby they're equivalent:
Now
Test.new('a') == Test.new('a')
andTest.new('a') === Test.new('a')
:)大多数时候,需要比较和/或可散列的对象由成员变量组成,这些成员变量要么是基元(整数、字符串等),要么本身是可比较/可散列的。在这些情况下,这个模块:
可以简单地包含在您的班级中来处理所有的繁忙工作。您所要做的就是定义一个“parts”方法,该方法返回构成对象状态的所有值:以
这种方式构建的对象是可比较的(它们具有 <、<=、==、>=、>、 != 和 equ?) 并且它们可以是哈希键。
Most of the time, an object you need to be comparable and/or hashable is composed of member variables which are either primitives (integers, strings, etc) or are themselves comparable/hashable. In those cases, this module:
can simply be included in your class to take care of all of the busywork. All you have to do is define a "parts" method that returns all of the values that comprise the object's state:
Objects built this way are comparable (they have <, <=, ==, >=, >, != and equ?) and they can be hash keys.