Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Hash with duplicate keys?

Tags:

Is it possible to create a hash in Ruby that allows duplicate keys?

I'm working in Ruby 1.9.2.

like image 611
B Seven Avatar asked Jul 24 '11 18:07

B Seven


People also ask

Can a Hash have duplicate keys in Ruby?

Short answer is no, hashes need to have unique keys.

Can a Hash have multiple values Ruby?

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.

Can a Key have multiple values Ruby?

Multiple Values For One Key Words are unique, but they can have multiple values (definitions) associated with them. You can do this in Ruby!

How do you Hash 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.


1 Answers

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} 
like image 131
steenslag Avatar answered Oct 05 '22 08:10

steenslag