Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,722 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!