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 trialDavid Quiroz
3,510 PointsDefining 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
KRIS NIKOLAISEN
54,972 PointsSome 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
3,510 PointsThanks, Kris! That got me to think about it in the right light. :D