Ruby Ruby Loops Ruby Loops The Ruby Loop

I need help adding 1 to the counter

In Ruby Loops, I am trying to add 1 to the counter for every time the (string) prints. I have tried various ways but have failed. Please help x

The task is as follows:

Challenge Task 1 of 1 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.

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

end end

2 Answers

Samuel Ferree
Samuel Ferree
31,710 Points

We can add one to variables in a couple ways, below are two common ways.

counter += 1
counter = counter + 1

Try putting one of them in the function below

def repeat(string, times) 
  fail "times must be 1 or more" if times < 1 
  counter = 0 
  loop do
    puts string
    # YOUR CODE HERE
    break if counter > times
  end
end
Jeff Lange
Jeff Lange
8,788 Points

This is more style preference, but it reads more clearly to me to avoid the break statement and use a while loop

while counter <= times do
  puts string
  # other code
end

Thank you everyone!