Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

hash

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:

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.

like image 244
splatoperator Avatar asked May 18 '14 03:05

splatoperator


People also ask

How do you iterate through an array in Ruby?

The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.

How do I iterate a hash in Ruby?

Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.


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 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
like image 67
Richard Cook Avatar answered Oct 14 '22 21:10

Richard Cook


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
like image 37
Varus Septimus Avatar answered Oct 14 '22 21:10

Varus Septimus