DollarChills
DollarChills

Reputation: 1086

`map` method on arrays within an array

I am using nested map on has_many association in following method

@trial.treatment_selections
.map { |ts| ts.establishment_methods.map { |em| em.final_establishment.to_f }}
# => [[10.2, 10.1, 10.1], [11.4, 11.4, 10.9]]

Here treatment_selections has_many establishment_methods.

I'm not sure how to get following array:

[10.2, 10.1, 10.1, 11.4, 11.4, 10.9]

Upvotes: 0

Views: 52

Answers (2)

Pramod Shinde
Pramod Shinde

Reputation: 1892

You can also use flatten method of an Array

@trial.treatment_selections
      .map { |ts| ts.establishment_methods.map { |em| em.final_establishment.to_f }}
      .flatten
#=> [10.2, 10.1, 10.1, 11.4, 11.4, 10.9]

Upvotes: 0

Raj
Raj

Reputation: 22926

Try flat_map:

<%= @trial.treatment_selections.flat_map { |ts| ts.establishment_methods.map { |em| em.final_establishment.to_f }} %>

Upvotes: 2

Related Questions