Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Inserting Key, Value elements in Hash

Tags:

ruby

hash

set

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

like image 783
user332550 Avatar asked May 04 '10 15:05

user332550


People also ask

How do I add a key to a hash in Ruby?

Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }. Additional key/value pairs can be added to the hash literal by separating them with commas.

How do you set a hash value in Ruby?

In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.

Does key exist in hash Ruby?

Overview. We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.

How do you create a key-value pair in Ruby?

Using {} braces: In this hash variable is followed by = and curly braces {}. Between curly braces {}, the key/value pairs are created.


2 Answers

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"]}>
like image 128
maček Avatar answered Oct 13 '22 07:10

maček


Probably, you want to merge two Hashes?

my_hash = { "key1"=> value1 }
another_hash = { "key2"=> value2 }
my_hash.merge(another_hash) # => { "key1"=> value1, "key2"=> value2 }
like image 36
Vanuan Avatar answered Oct 13 '22 05:10

Vanuan