Ruby Hash fetch函数
Hash#fetch()是一个Hash类方法,它从散列中返回一个给定键的值。如果没有其他参数,它将引发一个KeyError异常。
语法。Hash.fetch()
参数:哈希值
返回:从给定键的哈希值中获取数值
例子 #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"
输出:
Hash a fetch form : Not present, x
例子 #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"
输出:
Hash a fetch form : 100
Hash b fetch form : 100
Hash c fetch form : 200