tags:

views:

911

answers:

4

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?

A: 

It wouldn't change much, but you could use map:

x.map do |fruit|
    fruit.each { |k,v| puts v }
end
Evan Meagher
+10  A: 

So you want each hash to be converted to its values then joined with the values from the other hashes?

in = [{"fruit_id"=>"1"}, {"fruit_id"=>"2"}, {"fruit_id"=>"3"}]
out = in.map{ |item| item.values }.flatten

out will then be ["1","2","3"].

toholio
perfect, thank you!
aronchick
+3  A: 
a.inject([]) { |mem,obj| mem += obj.values }
Hemant Kumar
Nice and concise.
Jamie Love
injecting into an empty array is also known as collect (or map). see other answers here.
glenn jackman
Use << instead of += to append to arrays. It will be slightly faster as you won't be creating all those new array objects.
glenn jackman
<< and += are not the same. If you want to use "<<" you will have to flatten again. Anyways its just nitpick.
Hemant Kumar
+4  A: 

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
wombleton
I wish I could approve both - this is great too!
aronchick
Well, they're actually the same solution really. :)
toholio