Ruby Hash fetch_values()函数
Hash#fetch_values() 是一个Hash类方法,它返回包含与给定键相关的值的数组。如果没有其他参数,它将引发一个KeyError异常。
语法。Hash.fetch_values()
参数:哈希值
返回:包含与给定键相关的值的数组。
例子 #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]