如何在Ruby中使对象实例成为散列键? [英] How to make object instance a hash key in Ruby?

查看:97
本文介绍了如何在Ruby中使对象实例成为散列键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有几个成员变量的Foo类。当这个类的两个实例中的所有值都相等时,我希望这些对象相等。然后我会喜欢这些对象作为我的哈希键。当我现在尝试这样做时,哈希将每个实例视为不相等。

I have a class Foo with a few member variables. When all values in two instances of the class are equal I want the objects to be 'equal'. I'd then like these objects to be keys in my hash. When I currently try this, the hash treats each instance as unequal.

h = {}
f1 = Foo.new(a,b)
f2 = Foo.new(a,b)

f1在这一点上f2应该是相等的。

f1 and f2 should be equal at this point.

h[f1] = 7
h[f2] = 8
puts h[f1]

应该打印8

推荐答案

请参阅 http:// ruby​​- doc.org/core/classes/Hash.html


散列使用key.eql?测试
相等的密钥。如果您需要使用您自己的类的实例
作为哈希中的键
,建议您同时定义
eql?和散列方法。哈希
方法必须具有
a.eql?(b)意味着a.hash == b.hash。

Hash uses key.eql? to test keys for equality. If you need to use instances of your own classes as keys in a Hash, it is recommended that you define both the eql? and hash methods. The hash method must have the property that a.eql?(b) implies a.hash == b.hash.

eql?方法很容易实现:如果所有成员变量相同,则返回true。对于散列方法,请使用[@ data1,@ data2] .hash,如Marc-Andre在注释中所示。

The eql? method is easy to implement: return true if all member variables are the same. For the hash method, use [@data1, @data2].hash as Marc-Andre suggests in the comments.

这篇关于如何在Ruby中使对象实例成为散列键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆