Steve
Steve

Reputation: 101

Ruby: repeating a method n times all in one line

Suppose we have a method that returns a random string :

def return_random
  "random generated string #{Time.now}"
end

How to create a new string that is an addition of n times of return_random.

Exemple :

new_string = return_random + return_random + ... + return_random [n times]

Edit: Using return_random * n won't work because it's copying the string n times and not generating new ones.

Upvotes: 3

Views: 2398

Answers (1)

David Grayson
David Grayson

Reputation: 87446

This will do it:

new_string = n.times.collect { return_random }.inject(:+)

Upvotes: 13

Related Questions