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

David Quiroz
David Quiroz
3,510 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
3,510 Points

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