16

配列に対して X 回アクションを実行してから、その数値以外の結果を返したいことがよくあります。私が通常書くコードは次のとおりです。

  def other_participants
    output =[]
    NUMBER_COMPARED.times do
      output << Participant.new(all_friends.shuffle.pop, self)
    end
    output
  end

これを行うためのよりクリーンな方法はありますか?

4

3 に答える 3

31

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

于 2011-10-05T05:48:42.710 に答える
6

使用できます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) {|(*args), memo_obj| ... } → obj
each_with_object(obj) → an_enumerator

指定された任意のオブジェクトを使用して各要素に対して指定されたブロックを反復し、最初に指定されたオブジェクトを返します。
ブロックが指定されていない場合は、列挙子を返します。

于 2011-10-05T03:39:29.450 に答える
2

私はこのようなものが最高です

def other_participants
  shuffled_friends = all_friends.shuffle
  Array.new(NUMBER_COMPARED) { Participant.new(shuffled_friends.pop, self) }
end
于 2016-09-19T08:59:15.740 に答える