Let us say, we have a Hash that contains,
As Key and Value pair.
Now, let us say, we want to update the value of the Key, 5 with Is an one digit number.
5, Is an one digit number
Where 5 is the Key and Is an one digit number is the new Value.
We can update the entries of a Hash using two ways:
Let us see in the below example using the first way.
x = { 5 => "Is a Number", "John" => "Is a Name", "Ruby" => "Is a Language" } x[5] = "Is an one digit number" puts x
So, in the above code we have created a Hash using braces {} and Key and Value pairs.
x = { 5 => "Is a Number", "John" => "Is a Name", "Ruby" => "Is a Language" }
And initialised to the variable x.
Now, we are supposed to update the value of the Key, 5 with Is an one digit number.
So, we have used the below way to update it.
x[5] = "Is an one digit number"
And the entry for the Key 5 is updated in the Hash.
And we get the below output,
Let us see the second way of updating the Key Value using the update() Method.
x = { 5 => "Is a Number", "John" => "Is a Name", "Ruby" => "Is a Language" } x.update({5#{x}Is an one digit number"}) puts x)
So, in the above code we have created a Hash using braces {} and Key and Value pairs.
x = { 5 => "Is a Number", "John" => "Is a Name", "Ruby" => "Is a Language" }
And initialised to the variable x.
Now, we are supposed to update the value of the Key, 5 with Is an one digit number.
So, we have used the below way to update it.
x.update({5#{x}Is an one digit number"})
And the entry for the Key 5 is updated in the Hash.
And we get the below output,