Ruby Hash each_key函数

Ruby Hash each_key函数

Hash#each_key()是一个Hash类的方法,它可以找到嵌套的值,通过传递key作为参数,对Hash中的每个_key对调用一次block。

语法。Hash.each_key()

参数:哈希值

返回:为哈希中的key_value对调用一次块,以key为参数,否则,如果没有传递参数,则为Enumerator。

例子 #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}

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程