Ruby Hash each_pair()函数
Hash#each_pair()是一个Hash类方法,它可以通过传递key_value对作为参数,为Hash中的每一对找到嵌套值,并调用一次块。
语法。Hash.each_pair()
参数:哈希值
返回:以键值对为参数,为哈希中的键值对调用一次块,否则,如果没有传递参数,则为枚举器。
例子 #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}