How to add to an existing hash in Ruby

As for adding a key => value pair to an existing populated hash in Ruby, I am in the process of working through Apress "Beginning Ruby" and have just finished the hashes chapter.

I am trying to find the easiest way to achieve the same results with hashes as with arrays:

 x = [1, 2, 3, 4] x << 5 px 
+93
new-operator ruby hash
Jul 28 '11 at 18:22
source share
6 answers

If you have a hash, you can add elements to it by referencing them with the key:

 hash = { } hash[:a] = 'a' hash[:a] # => 'a' 

Here, like [ ] , an empty array is created, { } will create an empty hash.

Arrays have zero or more elements in a specific order, where elements can be duplicated. Hashes have zero or more elements organized by the key, where the keys may not be duplicated, but the values โ€‹โ€‹stored in these positions may be.

Ruby hashes are very flexible and can have keys of almost any type that you can throw at it. This makes it different from dictionary structures that you will find in other languages.

It is important to remember that the specific nature of the hash key often matters:

 hash = { :a => 'a' } # Fetch with Symbol :a finds the right value hash[:a] # => 'a' # Fetch with the String 'a' finds nothing hash['a'] # => nil # Assignment with the key :b adds a new entry hash[:b] = 'Bee' # This is then available immediately hash[:b] # => "Bee" # The hash now contains both keys hash # => { :a => 'a', :b => 'Bee' } 

Ruby on Rails is a bit confusing by providing a HashWithIndifferentAccess where it will be free to convert between the Symbol and String addressing methods.

You can also index almost everything, including classes, numbers, or other hashes.

 hash = { Object => true, Hash => false } hash[Object] # => true hash[Hash] # => false hash[Array] # => nil 

Hashes can be converted to arrays and vice versa:

 # Like many things, Hash supports .to_a { :a => 'a' }.to_a # => [[:a, "a"]] # Hash also has a handy Hash[] method to create new hashes from arrays Hash[[[:a, "a"]]] # => {:a=>"a"} 

When it comes to โ€œinsertingโ€ things into a hash, you can do this one at a time or use the merge method to combine hashes:

 { :a => 'a' }.merge(:b => 'b') # {:a=>'a',:b=>'b'} 

Note that this does not change the original hash, but instead returns a new one. If you want to combine one hash into another, you can use the merge! method merge! :

 hash = { :a => 'a' } # Returns the result of hash combined with a new hash, but does not alter # the original hash. hash.merge(:b => 'b') # => {:a=>'a',:b=>'b'} # Nothing has been altered in the original hash # => {:a=>'a'} # Combine the two hashes and store the result in the original hash.merge!(:b => 'b') # => {:a=>'a',:b=>'b'} # Hash has now been altered hash # => {:a=>'a',:b=>'b'} 

Like many methods in String and Array,! indicates that this is an on-site operation.

+179
Jul 28 '11 at 19:09
source share
 my_hash = {:a => 5} my_hash[:key] = "value" 
+63
Jul 28 '11 at 18:24
source share

If you want to add more than one:

 hash = {:a => 1, :b => 2} hash.merge! :c => 3, :d => 4 p hash 
+33
Jul 28 '11 at 18:28
source share
 x = {:ca => "Canada", :us => "United States"} x[:de] = "Germany" px 
+8
Jul 28 '11 at 18:25
source share
 hash {} hash[:a] = 'a' hash[:b] = 'b' hash = {:a => 'a' , :b = > b} 

You can get your key and value from user input, so you can use Ruby .to_sym to convert a string to a character, and .to_i converts the 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. 
0
Nov 22 '14 at 19:13
source share
 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 combined value.

 hash => {:a=>"a", :b=>"b"} 

But does not change the object of the caller

 hash = hash.merge({ c: 'c', d: 'd' }) => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} hash => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} 

Remapping does its job.

0
Jun 26 '19 at 13:36 on
source share



All Articles