How to make a ruby ​​block return an array of a variable in a block?

in 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 the disconnect object, which I don't want.

How can I make a block return an array of users?

thanks

+4
source share
1 answer

It looks like you want .collect() it:

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

Or using .map()

 user.trips.map(&:pickedpost).map(&:user) 
+3
source

Source: https://habr.com/ru/post/1412455/


All Articles