Open In App
Related Articles

Ruby | Hash fetch function

Improve Article
Improve
Save Article
Save
Like Article
Like

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"


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"


Output :

Hash a fetch form : 100

Hash b fetch form : 100

Hash c fetch form : 200


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 07 Jan, 2020
Like Article
Save Article
Previous
Next
Similar Reads