📜  红宝石 |散列 fetch_values()函数

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

红宝石 |散列 fetch_values()函数

Hash#fetch_values()是一个 Hash 类方法,它返回包含与给定键关联的值的数组。如果没有其他参数,它将引发 KeyError 异常。

示例 #1:

# Ruby code for Hash.fetch_values() method
   
# declaring Hash value
a = { "a" => 100, "b" => 200 }
   
# declaring Hash value
b = {"a" => 100}
   
   
# block condition
# fetch? Value
puts "Hash a fetch_values form : #{a.fetch_values("x"){|k| k.upcase}}\n\n"

输出 :

Hash a fetch_values form : ["X"]

示例 #2:

# Ruby code for Hash.fetch_values() 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_values Value
puts "Hash a fetch_values form : #{a.fetch_values("a")}\n\n"
  
puts "Hash b fetch_values form : #{b.fetch_values("a")}\n\n"
  
puts "Hash c fetch_values form : #{c.fetch_values("b")}\n\n"

输出 :

Hash a fetch_values form : [100]

Hash b fetch_values form : [100]

Hash c fetch_values form : [200]