📜  红宝石 |哈希获取函数

📅  最后修改于: 2022-05-13 01:55:31.440000             🧑  作者: Mango

红宝石 |哈希获取函数

Hash#fetch()是一个 Hash 类方法,它从给定键的哈希中返回一个值。如果没有其他参数,它将引发 KeyError 异常。

示例 #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