nested loop

E

Erwin

I know there is DRY way tow rite that, but I don't remember how


residence_rentals_ids = []
residences = user.franchise.residences
for residence in residences
residence_rentals_ids = residence.rentals.map {|rental|
rental[:id] }.compact
end


I tried unsuccessfully :

residence_rentals_ids = user.franchise.residences.each { |residence|
residence.rentals.map { |rental| rental[:id}.compact }

thanks for your lights

erwin
 
E

Erwin

I know there is DRY way tow rite that, but I don't remember how

residence_rentals_ids = []
residences = user.franchise.residences
 for residence in residences
     residence_rentals_ids = residence.rentals.map {|rental|
rental[:id] }.compact
end

I tried unsuccessfully :

residence_rentals_ids = user.franchise.residences.each { |residence|
residence.rentals.map { |rental| rental[:id}.compact   }

thanks for your lights

erwin

got it :
residence_rentals_ids = []
user.franchise.residences.each { |residence| residence.rentals.map { |
rental| residence_rentals_ids << rental[:id] }.compact }

but is there a way to avoid the residence_rentals_ids = [] line,
including the array initialization into a block ?
 
A

Adam Shelly

residence_rentals_ids = []
user.franchise.residences.each { |residence| residence.rentals.map { |
rental| residence_rentals_ids << rental[:id] }.compact }

but is there a way to avoid the residence_rentals_ids = [] line,
including the array initialization into a block ?

residence_rentals_ids = user.franchise.residences.map{ |residence|
residence.rentals.map { |rental| rental[:id] }.compact }.flatten
 
E

Erwin

I know there is DRY way tow rite that, but I don't remember how
residence_rentals_ids = []
residences = user.franchise.residences
 for residence in residences
     residence_rentals_ids = residence.rentals.map {|rental|
rental[:id] }.compact
end
I tried unsuccessfully :
residence_rentals_ids = user.franchise.residences.each { |residence|
residence.rentals.map { |rental| rental[:id}.compact   }
thanks for your lights
erwin
got it  :
residence_rentals_ids = []
user.franchise.residences.each { |residence| residence.rentals.map { |
rental| residence_rentals_ids << rental[:id] }.compact   }
but is there a way to avoid the residence_rentals_ids = []  line,
including the array initialization into a block ?

Generally you don't want a map without assigning the result to something.

Does this do what you want?

residence_rental_ids = user.franchise.residences.map{|residence|
residence.rentals.map{|rental| rental[:id] } }.flatten

-Michael

that's it... thanks a lot.. I was missing the .flatten functionality
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,202
Messages
2,571,055
Members
47,658
Latest member
jaguar32

Latest Threads

Top