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

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

红宝石 |散列 each_pair()函数

Hash#each_pair()是一个 Hash 类方法,它通过传递 key_value 对作为参数来查找嵌套值,该嵌套值为 hash 中的每一对调用一次块。

示例 #1:

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

输出 :

Hash a each_pair form : #

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

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

示例 #2:

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

输出 :

Hash a each_pair form : #

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

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