如何使Ruby块返回块中变量的数组?

4

在 Ruby 块中:

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

如何让代码返回一个用户数组?
如果我运行这个块:
user.trips.each { |trip| puts trip.pickedpost.user }

irb显示

#<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">] 

该块返回了一个行程对象的数组,而这不是我想要的。

我该如何使该块返回一个用户数组?

谢谢。

1个回答

3

看起来你想要的是使用.collect()方法:

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

或者使用.map()方法

user.trips.map(&:pickedpost).map(&:user)

谢谢,问题解决了!user.trips.map(&:pickedpost).map(&:user) - alexZ
user.trips.map { |trip| trip.pickedpost.user } 可能不够优雅,但更高效,因为它只在数组上迭代一次。 - Matheus Moreira

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接