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

3

16

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?

Haland answered 5/10, 2011 at 3:33 Comment(2)
I swear this isn't for reputation, but I really think you accepted the wrong answer. Collect is really EXACTLY the right one to use. Even if you make another answer an accept that one, I really think you should accept a map/collect answer for when someone else comes by and looks at this question.Austerity
I thought the same thing myself after experimenting so I switchedHaland
A
31

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

Austerity answered 5/10, 2011 at 5:48 Comment(0)
R
6

You could use 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

From the fine manual:

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

Iterates the given block for each element with an arbitrary object given, and returns the initially given object.
If no block is given, returns an enumerator.

Raven answered 5/10, 2011 at 3:39 Comment(2)
Imperative programmer! Rot in silicon hell!Taverner
@Andrew: Get off my lawn kid!Raven
B
2

I thing something like this is best

def other_participants
  shuffled_friends = all_friends.shuffle
  Array.new(NUMBER_COMPARED) { Participant.new(shuffled_friends.pop, self) }
end
Butlery answered 19/9, 2016 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.