如果我在C#/ Java中这样做,无论我需要创建一个新类并覆盖hashcode()/ equals()方法,但这似乎容易出错,因为我已经读过它了,我很想知道如果在这里有更好的选择.
解决方法 我正在直接复制Programming Ruby 1.9中的一段:Hash keys must respond to the message
hash
by returning a hash code,and the hash code for a given key must not change. The keys used in hashes must also be comparable usingeql?
. Ifeql?
returnstrue
for two keys,then those keys must also have the same hash code. This means that certain classes (such asArray
andHash
) can’t convenIEntly be used as keys,because their hash values can change based on their contents.
因此,您可以生成哈希,如[“#{source_ip}#{source_port}”,“#{dest_ip}#{dest_port}”,protocol.to_s] .sort.join.hash,以便结果相同时切换源和目标.
例如:
source_ip = "1.2.3.4"source_port = 1234dest_ip = "5.6.7.8"dest_port = 5678protocol = "http"def make_hash(s_ip,s_port,d_ip,d_port,proto) ["#{s_ip} #{s_port}","#{d_ip} #{d_port}",proto.to_s].sort.join.hashendputs make_hash(source_ip,source_port,dest_ip,dest_port,protocol)puts make_hash(dest_ip,source_ip,protocol)
即使两个调用之间的参数顺序不同,这也会输出相同的哈希值.将此功能正确地封装到类中是留给读者的练习.
总结以上是内存溢出为你收集整理的Ruby:我如何使用Hash获取多个键?全部内容,希望文章能够帮你解决Ruby:我如何使用Hash获取多个键?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)