Ruby Hash key()函数
Hash#key()是一个Hash类方法,它给出了与value对应的key值。如果值不存在,则返回nil。
语法。Hash.key()
参数:哈希值
返回:与该值对应的键
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