We can get the value of a given key of a Hash by using the fetch(key)
method. We only need to specify the key
we want to get. This way, it will give us the value of the key we have specified.
hash.fetch(key)
hash
: This is the Hash whose keys we want to access.
key
: This is the key whose value will be returned, if found.
This method returns the value for the given key
.
# create hashesh1 = {one: 1, two: 2, three: 3}h2 = {name: "okwudili", stack: "ruby"}h3 = {"foo": 0, "bar": 1}h4 = { a: 100, b: 200, c: 300 }# find key valuesputs h1.fetch(:two)puts h2.fetch(:name)puts h3.fetch(:foo)puts h4.fetch(:b)
fetch(key)
method on the Hashes, along with the arguments of the method. Then, we print the results to the console.