سؤال

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

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top