我使用 5 个字符串(协议(protocol)、源 IP 和端口、目标 IP 和端口)并使用它们将一些值存储在哈希中。问题是如果 IP 或端口在源和目标之间切换, key 应该是相同的。
如果我在 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 = 1234
dest_ip = "5.6.7.8"
dest_port = 5678
protocol = "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.hash
end
puts make_hash(source_ip, source_port, dest_ip, dest_port, protocol)
puts make_hash(dest_ip, dest_port, source_ip, source_port, protocol)
这将输出相同的散列,即使参数在两次调用之间的顺序不同。将此功能正确封装到一个类中作为练习留给读者。
关于Ruby:我怎样才能让一个散列接受多个键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2582059/