Ruby Hash with duplicate keys?

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

I'm working in Ruby 1.9.2.

Answers 1

  • 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 = { |h,k| h[k] = [] }
    h[:foo] << :bar
    h #=> {:foo=>[:bar]}
    h[:foo] << :baz
    h #=> {:foo=>[:bar, :baz]}

Related Articles