Ruby Ruby Loops Ruby Loops The Ruby Loop

David Quiroz
David Quiroz
807 Points

Defining a Method and taking a string x amount of times, then looping and breaking

Not sure what is being ask of me in this challenge:

The repeat method should take a string, and print it a specified number of times. Use loop and break to complete the method. Be sure to do the following: After printing the value of string, add 1 to the counter variable. Use an if statement together with the break keyword to break out of the loop once counter is equal to times.

My question is mainly what am I meant to do for this challenge?

Code Provided:

def repeat(string, times) fail "times must be 1 or more" if times < 1 counter = 0 loop do # YOUR CODE HERE

end end

Proposed Solution:

def repeat(string, times) fail "times must be 1 or more" if times < 1 counter = 0 loop do print "what is your name?" answer=gets.chomp print "#{answer}, " counter +=1 if counter ==5 break end end

Error given: "Bummer, try again"

2 Answers

Some hints

  • You only need to print string. This is the value of the string passed in by the challenge.
  • You are to break if counter == times. This is the maximum number of times the loop should run.

So for example if the challenge calls repeat("hi", 5) and it does, your code should print "hi" 5 times

David Quiroz
David Quiroz
807 Points

Thanks, Kris! That got me to think about it in the right light. :D