[ruby] How to add to an existing hash in Ruby

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

The answer is


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.


Examples related to ruby

Uninitialized Constant MessagesController Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Ruby - ignore "exit" in code Empty brackets '[]' appearing when using .where find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException) How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite? How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? How to update Ruby with Homebrew?

Examples related to new-operator

Java FileOutputStream Create File if not exists How to add to an existing hash in Ruby Expression must have class type Why should C++ programmers minimize use of 'new'? Creating an object: with or without `new` int *array = new int[n]; what is this function actually doing? Open button in new window? How to open in default browser in C# Print in new line, java Deleting an object in C++

Examples related to hash

php mysqli_connect: authentication method unknown to the client [caching_sha2_password] What is Hash and Range Primary Key? How to create a laravel hashed password Hashing a file in Python PHP salt and hash SHA256 for login password Append key/value pair to hash with << in Ruby Are there any SHA-256 javascript implementations that are generally considered trustworthy? How do I generate a SALT in Java for Salted-Hash? What does hash do in python? Hashing with SHA1 Algorithm in C#