📜  红宝石 |哈希反转()函数

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

红宝石 |哈希反转()函数

Hash#invert()是一种 Hash 类方法,它通过将键还原为值并将值还原为键来提供散列。

示例 #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"}