📜  红宝石 |散列 each_key函数

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

红宝石 |散列 each_key函数

Hash#each_key()是一个 Hash 类方法,它通过将键作为参数传递来查找嵌套值,该嵌套值为散列中的 each_key 对调用一次块。

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