Ruby Hash with duplicate keys?

前端 未结 2 1347
陌清茗
陌清茗 2020-11-29 09:05

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

I\'m working in Ruby 1.9.2.

2条回答
  •  感动是毒
    2020-11-29 09:56

    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]}
    

提交回复
热议问题