Ruby在Hash中插入Key,Value元素

use*_*550 12 ruby hash set

我想在我的哈希列表中添加元素,这些列表可以有多个值.这是我的代码.我不知道怎么解决它!

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
Run Code Online (Sandbox Code Playgroud)

提前谢谢了.

问候,

KOKO

mač*_*ček 11

我想这就是你要做的

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
#=> #<Dictionary:0x42d33c @data={"tall"=>["long", "word1", "word2"], "something"=>["anything", "foo", "bar"], "more"=>["yes"]}>

puts d['tall'].inspect
#=> ["long", "word1", "word2"]
Run Code Online (Sandbox Code Playgroud)

编辑

现在避免重复值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
#<Dictionary:0x42d48c @data={"foo"=>["bar", "baz", "bof", "zim"]}>
Run Code Online (Sandbox Code Playgroud)


Van*_*uan 9

可能你想合并两个哈希?

my_hash = { "key1"=> value1 }
another_hash = { "key2"=> value2 }
my_hash.merge(another_hash) # => { "key1"=> value1, "key2"=> value2 }
Run Code Online (Sandbox Code Playgroud)