在 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">]
该块返回了一个行程对象的数组,而这不是我想要的。
我该如何使该块返回一个用户数组?
谢谢。
user.trips.map { |trip| trip.pickedpost.user }
可能不够优雅,但更高效,因为它只在数组上迭代一次。 - Matheus Moreira