如何遍历哈希数组并以单个字符串返回值? [英] How do I iterate over an array of hashes and return the values in a single string?
问题描述
很抱歉,如果这很明显,我只是不明白.如果我有一系列的哈希值,例如:
Sorry if this obvious, I'm just not getting it. If I have an array of hashes like:
people = [{:name => "Bob", :occupation=> "Builder"}, {:name => "Jim", :occupation =>
"Coder"}]
我想遍历数组并输出类似"Bob:Builder"的字符串.我该怎么办?我知道如何进行迭代,但是我仍然有点迷路.现在,我有:
And I want to iterate over the array and output strings like: "Bob: Builder". How would I do it? I understand how to iterate, but I'm still a little lost. Right now, I have:
people.each do |person|
person.each do |k,v|
puts "#{v}"
end
end
我的问题是我不了解如何返回两个值,而仅返回每个值.我想念什么?
My problem is that I don't understand how to return both values, only each value separately. What am I missing?
谢谢您的帮助.
推荐答案
在这里:
puts people.collect { |p| "#{p[:name]}: #{p[:occupation]}" }
或者:
people.each do |person|
puts "#{person[:name]}: #{person[:occupation]}"
end
在回答有关访问数组中元素值的更一般的查询时,您需要知道people
是一个哈希数组.哈希具有keys
方法和values
方法,分别返回键和值.考虑到这一点,一个更通用的解决方案可能类似于:
In answer to the more general query about accessing the values in elements within the array, you need to know that people
is an array of hashes. Hashes have a keys
method and values
method which return the keys and values respectively. With this in mind, a more general solution might look something like:
people.each do |person|
puts person.values.join(': ')
end
这篇关于如何遍历哈希数组并以单个字符串返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!