Is it possible to create a hash in Ruby that allows duplicate keys?
I'm working in Ruby 1.9.2.
Short answer is no, hashes need to have unique keys.
Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.
Multiple Values For One Key Words are unique, but they can have multiple values (definitions) associated with them. You can do this in Ruby!
In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.
Two ways of achieving duplicate keys in a hash:
h1 = {} h1.compare_by_identity h1["a"] = 1 h1["a"] = 2 p h1 # => {"a"=>1, "a"=>2} h2 = {} a1 = [1,2,3] a2 = [1,2] h2[a1] = 1 h2[a2] = 2 a2 << 3 p h2 # => {[1, 2, 3]=>1, [1, 2, 3]=>2}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With