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
相關用法
- Ruby Hash dig()用法及代碼示例
- Ruby Hash each()用法及代碼示例
- Ruby Hash eql?用法及代碼示例
- Ruby Hash key()用法及代碼示例
- Ruby Hash key?()用法及代碼示例
- Ruby Hash any?()用法及代碼示例
- Ruby Hash each_key用法及代碼示例
- Ruby Hash empty?用法及代碼示例
- Ruby Range hash()用法及代碼示例
- Ruby Regexp hash()用法及代碼示例
- Ruby Hash include?()用法及代碼示例
- Ruby Hash inspect()用法及代碼示例
- Ruby Hash to_s()用法及代碼示例
- Ruby Hash keep_if()用法及代碼示例
- Ruby Hash each_pair()用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Ruby | Hash fetch function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。