我經常想對數組執行X次操作,然後返回除該數字以外的結果。我通常寫的代碼如下:乾淨的方式從Ruby中的X.times返回數組
def other_participants
output =[]
NUMBER_COMPARED.times do
output << Participant.new(all_friends.shuffle.pop, self)
end
output
end
有沒有更乾淨的方法來做到這一點?
我經常想對數組執行X次操作,然後返回除該數字以外的結果。我通常寫的代碼如下:乾淨的方式從Ruby中的X.times返回數組
def other_participants
output =[]
NUMBER_COMPARED.times do
output << Participant.new(all_friends.shuffle.pop, self)
end
output
end
有沒有更乾淨的方法來做到這一點?
聽起來你可以使用map/collect(它們是Enumerable上的同義詞)。它會返回一個數組,其內容是通過map/collect返回每次迭代的內容。
def other_participants
NUMBER_COMPARED.times.collect do
Participant.new(all_friends.shuffle.pop, self)
end
end
您不需要另一個變量或顯式的return語句。
http://www.ruby-doc.org/core/Enumerable.html#method-i-collect
你可以使用each_with_object
:
def other_participants
NUMBER_COMPARED.times.each_with_object([]) do |i, output|
output << Participant.new(all_friends.shuffle.pop, self)
end
end
each_with_object(OBJ){|(*參數),memo_obj | ...}→OBJ
each_with_object(OBJ)→an_enumerator迭代用於與給定的任意物體的每個元素的給定的塊,並返回最初給定的對象。
如果沒有給出塊,則返回一個枚舉器。
命令式程序員!在地獄裏腐爛! –
@Andrew:放下我的草坪小子! –
我像這樣的事情是最好的
def other_participants
Array.new(NUMBER_COMPARED) { Participant.new(all_friends.shuffle.pop, self) }
end
我發誓這不是名聲,但我真的覺得你接受了錯誤的答案。收集真的是正確的使用。即使你作出另一個答案並接受這個答案,我真的認爲你應該接受一個地圖/收集答案,以便別人來時看看這個問題。 – xaxxon
我在實驗後認爲自己也是一樣,所以我換了 –