How to iterate over an array of hashes and return values ​​in one line?

Sorry if this is obvious, I just don't get 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 lines like: "Bob: Builder". How can 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 do not understand how to return both values, only each value separately. What am I missing?

Thank you for your help.

+6
source share
2 answers

Here you go:

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

Or:

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

In response to a more general request for accessing values ​​in elements in an array, you need to know that people is an array of hashes. Hashes have a keys and values method that return keys and values, respectively. With this in mind, a more general solution might look something like this:

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

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 
0
source

Source: https://habr.com/ru/post/969449/


All Articles