Ruby Inserting Key, Value elements in Hash
38,519
Solution 1
I think this is what you're trying to do
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"]
Edit
Now avoids duplicate values thanks to 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"]}>
Solution 2
Probably, you want to merge two Hashes?
my_hash = { "key1"=> value1 }
another_hash = { "key2"=> value2 }
my_hash.merge(another_hash) # => { "key1"=> value1, "key2"=> value2 }
Author by
user332550
Updated on July 13, 2022Comments
-
user332550 almost 2 years
I want to add elements to my Hash lists, which can have more than one value. Here is my code. I don't know how I can solve it!
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
Many thanks in advance.
regards,
koko
-
glenn jackman about 14 yearsThe OP seemed to want to avoid duplicates, so you might want to use a Set instead of an Array for the hash values.
-
maček about 14 years@glenn, this avoids duplicate keys.
-
user332550 about 14 years@macek and @glenn Do you means something like that? def []=(key,value) if [email protected]?(keys) @data[key] << value else @data[value] = Set.new() end return @data[key] = [value] end regards, koko
-
maček about 14 years@kokogyi, you need to paste a set of inputs and expected output or I can't help you any further. Edit your question and I'll try to help.
-
glenn jackman about 14 years@macek, not duplicate keys, but duplicate values --
d['foo'] = 'bar'; d['foo']=%w{bar baz}; d['foo'] # ==> ["bar", "bar", "baz"]
-
Luke Mcneice over 12 yearsSpend a while looking for something that suited what I needed and this is exactly it!