Hash#fetch() is a Hash class method which returns a value from the hash for the given key. With no other arguments, it will raise a KeyError exception.
Syntax: Hash.fetch()
Parameter: Hash values
Return: value from the hash for the given key
Example #1 :
# Ruby code for Hash.fetch() method # declaring Hash value a = { "a" => 100, "b" => 200 } # declaring Hash value b = {"a" => 100} # declaring Hash value c = {"a" => 100, "c" => 300, "b" => 200} # Handling no key argument # fetch? Value puts "Hash a fetch form : #{a.fetch("x"){|el| "Not present, #{el}"}}\n\n" |
chevron_right
filter_none
Output :
Hash a fetch form : Not present, x
Example #2 :
# Ruby code for Hash.fetch() method # declaring Hash value a = { "a" => 100, "b" => 200 } # declaring Hash value b = {"a" => 100} # declaring Hash value c = {"a" => 100, "c" => 300, "b" => 200} # fetch Value puts "Hash a fetch form : #{a.fetch("a")}\n\n" puts "Hash b fetch form : #{b.fetch("a")}\n\n" puts "Hash c fetch form : #{c.fetch("b")}\n\n" |
chevron_right
filter_none
Output :
Hash a fetch form : 100 Hash b fetch form : 100 Hash c fetch form : 200
Recommended Posts:
- Ruby | Array class fetch() operation
- Ruby | Hash each_pair() function
- Ruby | Hash to_s() function
- Ruby | Hash invert() function
- Ruby | Hash include?() function
- Ruby | Hash inspect() function
- Ruby | Array class hash() function
- Ruby | Hash rassoc() function
- Ruby | Hash delete_if() function
- Ruby | Hash delete() function
- Ruby | Hash compare_by_identity? () function
- Ruby | Hash compact!() function
- Ruby | Hash compact() function
- Ruby | Hash clear() function
- Ruby | Hash assoc() function
- Ruby | Hash any?() function
- Ruby | Hash compare_by_identity () function
- Ruby | Hash flatten() function
- Ruby | Hash fetch_values() function
- Ruby | Hash eql? function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

