To add a key-value pair to a map in Ruby, you can use the subscript operator or the merge! method.
We can add a key-value pair to a map in Ruby using the subscript operator, which adds an element with a specific key and value to the map.
For example,
my_map
with some key-value pairs. In this example, the hash has string keys and integer values.puts
function.my_map = {
'one' => 1,
'two' => 2,
'three' => 3
}
# Add a key-value pair using subscript operator
my_map['four'] = 4
# Print the updated hash
puts my_map
{'one' => 1, 'two' => 2, 'three' => 3, 'four' => 4}
We can add multiple key-value pairs to a map in Ruby using the merge! method, which adds all key-value pairs from another hash.
For example,
my_map
with some key-value pairs. In this example, the hash has string keys and integer values.merge!
method to add multiple new key-value pairs to the hash. The merge!
method takes another hash containing the key-value pairs to be added.puts
function.my_map = {
'one' => 1,
'two' => 2,
'three' => 3
}
# Add multiple key-value pairs using merge! method
my_map.merge!({'four' => 4, 'five' => 5})
# Print the updated hash
puts my_map
{'one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5}
We can add a key-value pair to a map in Ruby using the store method, which adds the key-value pair if the key does not already exist.
For example,
my_map
with some key-value pairs. In this example, the hash has string keys and integer values.store
method to add a new key-value pair to the hash. The store
method takes two arguments: the key and the value to be added.puts
function.my_map = {
'one' => 1,
'two' => 2,
'three' => 3
}
# Add a key-value pair using store method
my_map.store('four', 4)
# Print the updated hash
puts my_map
{'one' => 1, 'two' => 2, 'three' => 3, 'four' => 4}
In this tutorial, we learned How to Add a Key-Value Pair to a Map in Ruby language with well detailed examples.