Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,721 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
    break if counter > times
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

Thank you everyone!