Ruby在Hash中插入Key,Value元素
我想在我的哈希列表中添加元素,这些列表可以有多个值。 这是我的代码。 我不知道怎么解决它!
class dictionary def initialize(publisher) @publisher=publisher @list=Hash.new() end def []=(key,value) @list << key unless @list.has_key?(key) @list[key] = value end end dic = Dictionary.new dic["tall"] = ["long", "word-2", "word-3"] p dic
提前谢谢了。
问候,
KOKO
我想这就是你要做的
class Dictionary def initialize() @data = Hash.new { |hash, key| hash[key] = [] } end def [](key) @data[key] end def []=(key,words) @data[key] += [words].flatten @data[key].uniq! end end d = Dictionary.new d['tall'] = %w(long word1 word2) d['something'] = %w(anything foo bar) d['more'] = 'yes' puts d.inspect #=> #["long", "word1", "word2"], "something"=>["anything", "foo", "bar"], "more"=>["yes"]}> puts d['tall'].inspect #=> ["long", "word1", "word2"]
编辑
现在Array#uniq!
避免重复值Array#uniq!
。
d = Dictionary.new d['foo'] = %w(bar baz bof) d['foo'] = %w(bar zim) # bar will not be added twice! puts d.inspect #["bar", "baz", "bof", "zim"]}>
可能你想合并两个哈希?
my_hash = { "key1"=> value1 } another_hash = { "key2"=> value2 } my_hash.merge(another_hash) # => { "key1"=> value1, "key2"=> value2 }