Ruby Hash each_key()函数
Hash#each_key()是一个Hash类的方法,它通过传递键对作为参数,对Hash中的每个键都调用一次块来找到嵌套的值。
语法。Hash.each_key()
参数:哈希值
返回:对于哈希中的每个键,以键为参数调用一次块,否则,如果没有传递参数,则调用枚举器。
例子 #1 :
# Ruby code for Hash.each_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}
# each Value
puts "Hash a each_key form : #{a.each_key()}\n\n"
puts "Hash b each_key form : #{b.each_key {|key| puts "#{key}"}}\n\n"
puts "Hash c each_key form : #{c.each_key {|value| puts "#{value}"}}\n\n"
输出:
Hash a each_key form : #
a
c
b
Hash b each_key form : {:a=>100, :c=>300, :b=>200}
a
Hash c each_key form : {:a=>100}
例子 #2 :
# Ruby code for Hash.each_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}
# each Value
puts "Hash a each_key form : #{a.each_key()}\n\n"
puts "Hash b each_key form : #{b.each_key {|key| puts "#{key}"}}\n\n"
puts "Hash c each_key form : #{c.each_key {|value| puts "#{value}"}}\n\n"
输出:
Hash a each_key form : #
a
Hash b each_key form : {"a"=>100}
a
c
b
Hash c each_key form : {"a"=>100, "c"=>300, "b"=>200}