2013-11-23 82 views
0

我似乎用下面的模式編寫了很多方法,好像應該有更好的方法。有沒有一個這樣或更好的做法?重構一個ruby方法

def combine_roster(roster) 
    rstr = [] 
    roster.each do |r| 
    rstr << r.user 
    end 
    rstr 
end 
+0

http://ruby-doc.org/core -2.0.0/Array.html#method-i-collect(又名地圖) –

+2

http://codereview.stackexchange.com – Phrogz

+0

Phrogz - 不錯。不知道存在。謝謝。 –

回答

5

是的,您可以使用map命令。下面是手短版本你正在嘗試做的事:

roster.map(&:user) # if roster = [r1, r2, r3] then the output will be [r1.user, r2.user, r3.user] 

你可以閱讀更多關於Ruby的數組API中的地圖功能:http://ruby-doc.org/core-2.0.0/Array.html#method-i-map