带有重复键的Ruby Hash? [英] Ruby Hash with duplicate keys?
本文介绍了带有重复键的Ruby Hash?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在 Ruby 中创建允许重复键的哈希?
Is it possible to create a hash in Ruby that allows duplicate keys?
我在使用 Ruby 1.9.2.
I'm working in Ruby 1.9.2.
推荐答案
这有点违背散列的目的,不是吗?
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]}
这篇关于带有重复键的Ruby Hash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文