In Ruby, a hash is a collection of key-value pairs which are stored unordered. Each key is unique, and it’s associated with a value. Hashes are useful when you want to store and access data using keys instead of indexes, like in arrays. In this blog post, we will learn how to add key-value pairs to a hash in Ruby.
Creating a hash
First of all, let’s create an empty hash. You can create an empty hash using the following syntax:
my_hash = {}
Adding key-value pairs to a hash
There are several ways to add key-value pairs to a hash in Ruby.
1. Using the []= operator
You can use the []= operator to add a key-value pair to a hash, like this:
my_hash[key] = value
For example:
my_hash = {} my_hash["name"] = "John" my_hash["age"] = 25 puts my_hash # Output: {"name"=>"John", "age"=>25}
2. Using the store method
Another way to add a key-value pair to a hash is by using the store method:
my_hash.store(key, value)
For example:
my_hash = {} my_hash.store("name", "John") my_hash.store("age", 25) puts my_hash # Output: {"name"=>"John", "age"=>25}
3. Using the merge! method
You can also add key-value pairs to a hash by using the merge! method. This method is useful when you want to add multiple key-value pairs at once:
my_hash.merge!(new_key_value_pairs)
For example:
my_hash = {} my_hash.merge!({"name" => "John", "age" => 25}) puts my_hash # Output: {"name"=>"John", "age"=>25}
Conclusion
In this blog post, we learned how to add key-value pairs to a hash in Ruby using different methods. The []= operator is the most common and simple way to add key-value pairs to a hash, but you can also use the store or merge! methods if you prefer. Choose the one that best suits your needs and coding style.