📜  红宝石 |散列 each()函数

📅  最后修改于: 2022-05-13 01:54:32.814000             🧑  作者: Mango

红宝石 |散列 each()函数

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

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