2012-05-15 62 views
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">] 

塊返回行程目標,這是不是我想要的數組。

如何讓塊返回用戶數組?

感謝

回答

3

看起來你想要的是.collect()它:

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

或者使用.map()

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

謝謝你,解決我的問題! user.trips.map(&:pickedpost).map(&:user) – alexZ

+0

'user.trips.map {| trip | trip.pickedpost.user}'可能不夠優雅,但應該更高效,因爲它只遍歷數組一次。 –