Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 290
Jack Kinsella Avatar asked Oct 05 '11 03:10

Jack Kinsella


People also ask

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

What does the .each method do in Ruby?

The each{} method allows one loop through the elements of an array to perform operations on them. It is an enumerator function that allows you to iterate over elements of an array and returns an array.

Can you print an array in Ruby?

Ruby printing array contents The array as a parameter to the puts or print method is the simplest way to print the contents of the array. Each element is printed on a separate line. Using the inspect method, the output is more readable. The line prints the string representation of the array to the terminal.


3 Answers

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

like image 114
xaxxon Avatar answered Sep 18 '22 17:09

xaxxon


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.

like image 44
mu is too short Avatar answered Sep 20 '22 17:09

mu is too short


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
like image 35
cmantas Avatar answered Sep 20 '22 17:09

cmantas