📜  红宝石 |哈希键()函数

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

红宝石 |哈希键()函数

Hash#key()是一个 Hash 类方法,它给出了键值对应的值。如果值不存在,则返回 nil。

示例 #1:

# Ruby code for Hash.key() 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}
  
  
# key Value
puts "Hash a key form : #{a.key(200)}\n\n"
  
puts "Hash b key form : #{b.key(100)}\n\n"
  
puts "Hash c key form : #{c.key(200)}\n\n"

输出 :

Hash a key form : b

Hash b key form : a

Hash c key form : 

示例 #2:

# Ruby code for Hash.key() 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}
  
# key Value
puts "Hash a key form : #{a.key(200)}\n\n"
  
puts "Hash b key form : #{b.key(100)}\n\n"
  
puts "Hash c key form : #{c.key(200)}\n\n"

输出 :

Hash a key form : b

Hash b key form : a

Hash c key form : b