红宝石 |哈希键()函数
Hash#keys()是一个 Hash 类方法,它提供一个包含哈希中存在的所有键的数组。
Syntax: Hash.keys()
Parameter: Hash values
Return: array with all the keys present in the hash
示例 #1:
# Ruby code for Hash.keys() 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}
# keys Value
puts "Hash a keys form : #{a.keys()}\n\n"
puts "Hash b keys form : #{b.keys()}\n\n"
puts "Hash c keys form : #{c.keys()}\n\n"
输出 :
Hash a keys form : [:a, :b]
Hash b keys form : [:a, :c, :b]
Hash c keys form : [:a]
示例 #2:
# Ruby code for Hash.keys() 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}
# keys Value
puts "Hash a keys form : #{a.keys()}\n\n"
puts "Hash b keys form : #{b.keys()}\n\n"
puts "Hash c keys form : #{c.keys()}\n\n"
输出 :
Hash a keys form : ["a", "b"]
Hash b keys form : ["a"]
Hash c keys form : ["a", "c", "b"]