Hash#invert()是一種Hash類方法,它通過將鍵恢複為值並將值恢複為鍵來提供哈希。
用法:Hash.invert()
參數:散列值
返回:通過將鍵還原為值和將值還原為鍵進行哈希
示例1:
# Ruby code for Hash.invert() method
# declaring Hash value
a = {a:100, b:200}
# declaring Hash value
b = {a:100, c:300, b:200}
# declaring Hash value
c = {a:100}
# invert Value
puts "Hash a invert form : #{a.invert()}\n\n"
puts "Hash b invert form : #{b.invert()}\n\n"
puts "Hash c invert form : #{c.invert()}\n\n"
輸出:
Hash a invert form : {100=>:a, 200=>:b} Hash b invert form : {100=>:a, 300=>:c, 200=>:b} Hash c invert form : {100=>:a}
示例2:
# Ruby code for Hash.invert() 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}
# invert Value
puts "Hash a invert form : #{a.invert()}\n\n"
puts "Hash b invert form : #{b.invert()}\n\n"
puts "Hash c invert form : #{c.invert()}\n\n"
輸出:
Hash a invert form : {100=>"a", 200=>"b"} Hash b invert form : {100=>"a"} Hash c invert form : {100=>"a", 300=>"c", 200=>"b"}
相關用法
- Ruby Hash key?()用法及代碼示例
- Ruby Hash dig()用法及代碼示例
- Ruby Hash any?()用法及代碼示例
- Ruby Hash each()用法及代碼示例
- Ruby Hash eql?用法及代碼示例
- Ruby Hash key()用法及代碼示例
- Ruby Hash flatten()用法及代碼示例
- Ruby Hash fetch_values()用法及代碼示例
- Ruby Range hash()用法及代碼示例
- Ruby Hash compare_by_identity()用法及代碼示例
- Ruby Hash to_s()用法及代碼示例
- Ruby Hash inspect()用法及代碼示例
- Ruby Hash keys()用法及代碼示例
- Ruby Hash fetch用法及代碼示例
- Ruby Hash each_key用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Ruby | Hash invert() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。