Is it possible to create a hash in Ruby that allows duplicate keys?
I'm working in Ruby 1.9.2.
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}
compare_by_identity works by comparing object_id's, normal hashes compare by comparing the result of the eql? method.h1['a'] two times, a string object gets created with different ids. This is not the case in som other versions. In other versions when you write h1['a'] twice the id of that 'a' will be the same each time. A workaround is to do h1['a'.clone] to create a new string object.This would kinda defeat the purpose of a hash, wouldn't it?
If you want a key to point to multiple elements, make it point to an array:
h = Hash.new { |h,k| h[k] = [] }
h[:foo] << :bar
h #=> {:foo=>[:bar]}
h[:foo] << :baz
h #=> {:foo=>[:bar, :baz]}
attrs = { ..., displayName: user.short_name, objectClass: "organizationPerson", objectClass: "person", objectClass: "top", objectClass: "user", i }
Hashthat has two entries, each of which with the same exact key?