ruby 如何遍历哈希数组并返回单个字符串中的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23718284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:29:53  来源:igfitidea点击:

How do I iterate over an array of hashes and return the values in a single string?

rubyhash

提问by splatoperator

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"}]

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:

我想遍历数组并输出字符串,例如:“Bob:Builder”。我该怎么做?我知道如何迭代,但我还是有点迷茫。现在,我有:

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?

我的问题是我不明白如何返回两个值,只分别返回每个值。我错过了什么?

Thank you for your help.

感谢您的帮助。

回答by Richard Cook

Here you go:

干得好:

puts people.collect { |p| "#{p[:name]}: #{p[:occupation]}" }

Or:

或者:

people.each do |person|
  puts "#{person[:name]}: #{person[:occupation]}"
end

In answer to the more general query about accessing the values in elements within the array, you need to know that peopleis an array of hashes. Hashes have a keysmethod and valuesmethod which return the keys and values respectively. With this in mind, a more general solution might look something like:

为了回答有关访问数组中元素值的更一般查询,您需要知道这people是一个散列数组。哈希有一个keys方法和values方法,分别返回键和值。考虑到这一点,更通用的解决方案可能如下所示:

people.each do |person|
  puts person.values.join(': ')
end

回答by Varus Septimus

Will work too:

也将工作:

people.each do |person|
  person.each do |key,value|
    print key == :name ? "#{value} : " : "#{value}\n"
  end
end

Output:

输出:

Bob : Builder
Jim : Coder