Hash#each_key()是一種Hash類方法,該方法通過將鍵作為參數傳遞來找到對哈希中的each_key對調用一次塊的嵌套值。
用法:Hash.each_key()
參數:散列值
返回:為哈希中的key_value對調用一次塊,並使用key作為參數;否則,如果未傳遞任何參數,則為Enumerator。
示例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}
相關用法
- Ruby Hash key()用法及代碼示例
- Ruby Hash any?()用法及代碼示例
- Ruby Hash dig()用法及代碼示例
- Ruby Hash each()用法及代碼示例
- Ruby Hash key?()用法及代碼示例
- Ruby Hash eql?用法及代碼示例
- Ruby Vector hash()用法及代碼示例
- Ruby Hash values用法及代碼示例
- Ruby Hash empty?用法及代碼示例
- Ruby Hash each_key()用法及代碼示例
- Ruby Hash to_s()用法及代碼示例
- Ruby Hash invert()用法及代碼示例
- Ruby Hash has_key?()用法及代碼示例
- Ruby Hash keys()用法及代碼示例
- Ruby Hash keep_if()用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Ruby | Hash each_key function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。