Ruby Hash each()函数

Ruby Hash each()函数

Hash#each()是一个Hash类方法,它通过传递键值对作为参数,对Hash中的每个键都调用一次块来找到嵌套的值。

语法。Hash.each()

参数:哈希值

返回:为哈希中的每个键调用一次块,否则,如果没有传递参数,则为枚举器。

例子 #1 :

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

输出:

Hash a each form : #

[:a, 100]
[:c, 300]
[:b, 200]
Hash b each form : {:a=>100, :c=>300, :b=>200}

[:a, 100]
Hash c each form : {:a=>100}

例子 #2 :

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

输出:

Hash a each form : #

["a", 100]
Hash b each form : {"a"=>100}

["a", 100]
["c", 300]
["b", 200]
Hash c each form : {"a"=>100, "c"=>300, "b"=>200}

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程