aronchick aronchick - 11 months ago 61
Ruby Question

Flatten an array of hashes in ruby

I have some simple code that looks like this:

fruit.each do |c|
c.each do |key, value|
puts value

This works fine, but it feels un-ruby like. My goal is to take this array:

[{"fruit_id"=>"1"}, {"fruit_id"=>"2"}, {"fruit_id"=>"3"}]

And convert it to this:

[ "1", "2", "3" ]


Answer Source

If it's in Rails or if you have to_proc defined, you can go a little bit shorter than @toholio's solution:

arr = [{"fruit_id"=>"1"}, {"fruit_id"=>"2"}, {"fruit_id"=>"3"}]
out = # => ["1", "2", "3"]