Ruby:我怎样才能让一个散列接受多个键?

标签 ruby hash

我使用 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 using eql?. If eql? returns true for two keys, then those keys must also have the same hash code. This means that certain classes (such as Array and Hash) 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/

相关文章:

ruby-on-rails - Rails - 如何将一个模型中的值调用到另一个模型中

javascript - Javascript 中的 CityHash

python - 是否可以通过 django 管理面板动态添加新字段

ruby - Mechanize 的 getaddrinfo 错误

javascript - Hyperstack 中的高阶组件

ruby - 如何使用 Ruby 自动化 Windows Run 应用程序

c++ - boost::hash<double> 在 RHEL 5.4 64 位上的奇怪行为

arrays - 旧版 Perl 中的警告消息

algorithm - rsync算法如何正确识别重复 block ?

ruby-on-rails - Rails Cucumber 测试 - 将表单数据发送到方法