在Ruby中从X.times返回数组的干净方法

Jac*_*lla 15 ruby code-cleanup

我经常想对数组执行X次操作,然后返回除该数字之外的结果.我经常写的代码如下:

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

有更清洁的方法吗?

xax*_*xon 24

听起来你可以使用map/collect(它们是Enumerable的同义词).它返回一个数组,其内容是每次迭代通过map/collect返回的内容.

def other_participants
  NUMBER_COMPARED.times.collect do
    Participant.new(all_friends.shuffle.pop, self)
  end
end
Run Code Online (Sandbox Code Playgroud)

您不需要另一个变量或显式返回语句.

http://www.ruby-doc.org/core/Enumerable.html#method-i-collect


mu *_*ort 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
Run Code Online (Sandbox Code Playgroud)

精细手册:

each_with_object(obj){|(*args),memo_obj | ...}→obj
each_with_object(obj)→an_enumerator

使用给定的任意对象迭代每个元素的给定块,并返回最初给定的对象.
如果没有给出块,则返回枚举器.

  • 势在必行的程序员!在硅地狱腐烂! (2认同)
  • @Andrew:离开我的草坪小子! (2认同)