oheydrew
oheydrew

Reputation: 36

Ruby .times method returns variable instead of output

In order to pass an rspec test, I need to get a simple string to be returned "num" amount of times. I've been googling and it seems the .times method should help. In theory from what I can see:

num = 2
string = "hello"

num.times do
  string
end

...Should work? But the output continues to return as "2", or whatever "num" is equal to. I can get it to "puts 'hello'" twice, but it still returns "2" after printing "hellohello".

Also tried

num.times { string }

Am I missing something fundamental about the .times method, here? Or should I be going about this another way?

Upvotes: 0

Views: 1400

Answers (2)

Eric Duminil
Eric Duminil

Reputation: 54283

times will repeat the execution of the block: string will be interpreted twice, but the value won't be used for anything. num.times will return num. You can check it in a Ruby console :

> 2.times{ puts "hello" }
hello
hello
 => 2 

You don't need a loop, you need concatenation:

string = "hello"
string + string
# "hellohello"
string + string + string
# "hellohellohello"

Or just like with numbers, you can use multiplication to avoid multiple additions :

string * 3
# "hellohellohello"
num = 2
string * num
# "hellohello"

If you need a list with 2 string elements, you can use :

[string] * num
# ["hello", "hello"]

or

Array.new(num) { string }
# ["hello", "hello"]

If you want to join the strings with a space in the middle :

Array.new(num, string).join(' ')
# "hello hello"

Just for fun, you could also use :

[string] * num * " "

but it's probably not really readable.

Upvotes: 3

Pend
Pend

Reputation: 752

Is this the behavior you're looking for?

def repeat(count, text)
  text * count
end

repeat(2, "hello") #  => "hellohello"

(No steps were taken to defend against bad input)

Upvotes: 0

Related Questions