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?
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.
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.
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.
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"]
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"]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With