Jack Kinsella Jack Kinsella - 2 months ago 15
Ruby Question

Clean way to return an array from X.times in Ruby

I often want to perform an action on an array X times then return a result other than that number. The code I usually write is the following:

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


Is there a cleaner way to do this?

Answer

sounds like you could use map/collect (they are synonyms on Enumerable). it returns an array with the contents being the return of each iteration through the map/collect.

def other_participants
  NUMBER_COMPARED.times.collect do
    Participant.new(all_friends.shuffle.pop, self)
  end
end

You don't need another variable or an explicit return statement.

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