In regards to adding an key => value
pair to an existing populated hash in Ruby, I'm in the process of working through Apress' Beginning Ruby and have just finished the hashes chapter.
I am trying to find the simplest way to achieve the same results with hashes as this does with arrays:
x = [1, 2, 3, 4]
x << 5
p x
This question is related to
ruby
new-operator
hash
If you want to add more than one:
hash = {:a => 1, :b => 2}
hash.merge! :c => 3, :d => 4
p hash
hash {}
hash[:a] = 'a'
hash[:b] = 'b'
hash = {:a => 'a' , :b = > b}
You might get your key and value from user input, so you can use Ruby .to_sym can convert a string to a symbol, and .to_i will convert a string to an integer.
For example:
movies ={}
movie = gets.chomp
rating = gets.chomp
movies[movie.to_sym] = rating.to_int
# movie will convert to a symbol as a key in our hash, and
# rating will be an integer as a value.
my_hash = {:a => 5}
my_hash[:key] = "value"
x = {:ca => "Canada", :us => "United States"}
x[:de] = "Germany"
p x
You can use double splat operator which is available since Ruby 2.0:
h = { a: 1, b: 2 }
h = { **h, c: 3 }
p h
# => {:a=>1, :b=>2, :c=>3}
hash = { a: 'a', b: 'b' }
=> {:a=>"a", :b=>"b"}
hash.merge({ c: 'c', d: 'd' })
=> {:a=>"a", :b=>"b", :c=>"c", :d=>"d"}
Returns the merged value.
hash
=> {:a=>"a", :b=>"b"}
But doesn't modify the caller object
hash = hash.merge({ c: 'c', d: 'd' })
=> {:a=>"a", :b=>"b", :c=>"c", :d=>"d"}
hash
=> {:a=>"a", :b=>"b", :c=>"c", :d=>"d"}
Reassignment does the trick.
Source: Stackoverflow.com