aronchick aronchick - 2 months ago 6
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
end
end


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


Thoughts?

Answer

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 = arr.map(&:values).flatten # => ["1", "2", "3"]
Comments