Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten an array of hashes in ruby

Tags:

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?

like image 569
aronchick Avatar asked Jun 24 '09 01:06

aronchick


People also ask

What is flatten in Ruby?

The flatten() is an inbuilt method in Ruby returns a new set that is a copy of the set, flattening each containing set recursively. Syntax: s1.flatten() Parameters: The function does not takes any parameter. Return Value: It returns a boolean value. It returns true if the set is empty or it returns false.

What is array of hashes in Ruby?

Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements.

How do you turn an array into a hash in Ruby?

The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.


2 Answers

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"]
like image 96
wombleton Avatar answered Sep 22 '22 01:09

wombleton


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

like image 44
toholio Avatar answered Sep 24 '22 01:09

toholio