ruby - How do I iterate over an array of hashes and return the values in a single string? -
sorry if obvious, i'm not getting it. if have array of hashes like:
people = [{:name => "bob", :occupation=> "builder"}, {:name => "jim", :occupation => "coder"}]
and want iterate on array , output strings like: "bob: builder". how it? understand how iterate, i'm still little lost. right now, have:
people.each |person| person.each |k,v| puts "#{v}" end end
my problem don't understand how return both values, each value separately. missing?
thank help.
here go:
puts people.collect { |p| "#{p[:name]}: #{p[:occupation]}" }
or:
people.each |person| puts "#{person[:name]}: #{person[:occupation]}" end
in answer more general query accessing values in elements within array, need know people
array of hashes. hashes have keys
method , values
method return keys , values respectively. in mind, more general solution might like:
people.each |person| puts person.values.join(': ') end
Comments
Post a Comment