[英]How do I loop through an array of hashes to get values of a nested array?
我想遍歷並一次打印出關鍵“愛好”的值
people = [
{
"first_name" => "Robert",
"last_name" => "Garcia",
"hobbies" => ["basketball", "chess", "phone tag"]
},
{
"first_name" => "Molly",
"last_name" => "Barker",
"hobbies" => ["programming", "reading", "jogging"]
},
{
"first_name" => "Kelly",
"last_name" => "Miller",
"hobbies" => ["cricket", "baking", "stamp collecting"]
}
]
這是我在被難倒之前想到的
people.each { |inner|
inner.each { |key, value|
p value
}
}
你可以這樣做:
people.each do |person|
puts "- #{person['first_name']} #{person['last_name']}"
person['hobbies'].each { |hobby| puts hobby }
end
這將生成這個 output:
- Robert Garcia
basketball
chess
phone tag
- Molly Barker
programming
reading
jogging
- Kelly Miller
cricket
baking
stamp collecting
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.