Я хочу добавить элементы к своим Хэш-спискам, которые могут иметь больше чем одно значение. Вот мой код. Я не знаю, как я могу решить его!
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
#=> #<Dictionary:0x42d33c @data={"tall"=>["long", "word1", "word2"], "something"=>["anything", "foo", "bar"], "more"=>["yes"]}>
puts d['tall'].inspect
#=> ["long", "word1", "word2"]
Теперь избежать дублирования значения благодаря 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"]}>