4

in a ruby block:

user.trips.each { |trip| trip.pickedpost.user }

How can I make the code return an array of users?

If I run the block

user.trips.each { |trip| puts trip.pickedpost.user }

irb shows

#<User:0x007fd1ab9e2148>
#<User:0x007fd1aacf3dd8>
 => [#<Trip id: 18, pickedpost_id: 25, volunteer_id: 33, created_at: "2012-05-14 23:28:36",    updated_at: "2012-05-14 23:28:36">, #<Trip id: 20, pickedpost_id: 20, volunteer_id: 33, created_at: "2012-05-15 00:12:39", updated_at: "2012-05-15 00:12:39">] 

the block returns an array of trip object, which is not what I want.

How can I make the block return an user array?

Thanks

1 Answer 1

3

Looks like what you want is to .collect() it:

user.trips.collect { |trip| trip.pickedpost.user }

Or using .map()

user.trips.map(&:pickedpost).map(&:user)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that solves my problem! user.trips.map(&:pickedpost).map(&:user)
user.trips.map { |trip| trip.pickedpost.user } might not be as elegant but should be more efficient since it only iterates over the array once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.