1
比方說,我想訪問的哈希值是這樣的:在Ruby中,#each_pair在通過散列迭代時優於#each的優點是什麼?
munsters = {
"Herman" => { "age" => 32, "gender" => "male" },
"Lily" => { "age" => 30, "gender" => "female" },
"Grandpa" => { "age" => 402, "gender" => "male" },
"Eddie" => { "age" => 10, "gender" => "male" },
"Marilyn" => { "age" => 23, "gender" => "female"}
}
我可以用#each
有兩個參數:
munsters.each do |key, value|
puts "#{name} is a #{values["age"]}-year-old #{values["gender"]}."
end
或者我可以用#each_pair
有兩個參數:
munsters.each_pair do |key, value|
puts "#{name} is a #{values["age"]}-year-old #{values["gender"]}."
end
也許兩者之間的差異並沒有在這個簡單的例子中證明,但有人可以幫助m e瞭解使用#each_pair
優於#each
的優勢?
@lurker你可以用'#each_pair'完成相同的操作。 –