Ruby Hash invert()函数
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"}