I directly copy the paragraph from "Ruby 1.9 Programming":
The hash keys must respond to the hash message, returning a hash code, and the hash code for the given key should not change. Keys used in hashes should also be comparable using eql? . If eql? returns true for two keys, then these keys must also have the same hash code. This means that some classes (such as Array and hash ) cannot be conveniently used as keys, because their hash values ββmay vary depending on their contents.
Thus, you can create your hash as something like ["#{source_ip} #{source_port}", "#{dest_ip} #{dest_port}", protocol.to_s].sort.join.hash so that the result is identical when switching source and destination.
For instance:
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)
This will result in the same hash, even if the arguments are in a different order between the two calls. The proper encapsulation of this functionality in a class is left as an exercise for the reader.
source share