Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flat_map in Ruby 1.8.7

Using Ruby 1.8.7, is there built-in functionality similar to Array.map which allows for the return of multiple values instead of just one? E.g. I have an array and each element contains an array - I want to end up with all values from the inner arrays. For instance, an array of states where each as an array of counties - I want a an array of ALL counties.

@states.map_many { |o| o[:states] }

Same as Array.flat_map in newer versions of Ruby. http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-flat_map

like image 930
Josh M. Avatar asked Jan 28 '26 11:01

Josh M.


1 Answers

Just use array.map { ... }.flatten.

To get all counties, you'd use...

@counties = @states.map { |o| o[:states] }.flatten

If you wish to flatten by only one level (which flat_map does in current versions of Ruby), you can pass a 1 to flatten. This is unnecessary for your example, as you are building an array with at most two dimensions.

like image 83
meagar Avatar answered Jan 31 '26 23:01

meagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!