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 trialRicardo Hill-Henry
38,442 Points"The Ruby Loop" objective
I'm really sorta lost as to what's wrong with this. With the code below, I get an unexpected keyword_end syntax error.
Here's the objective: Using the loop construct, add the current value of number to the numbers array. Inside of the loop, add 1 to the number variable. Use the break keyword to exit the loop once the numbers array has 3 items.
numbers = []
number = 0
# write your loop here
loop do
numbers.push(number)
if numbers.length == 3
break
end
number++
end
After some playing around, I removed number++ and the objective passed. However, I don't understand why. Wouldn't it just be an infinite loop without number++?
numbers = []
number = 0
# write your loop here
loop do
numbers.push(number)
if numbers.length == 3
break
end
# number++
end
1 Answer
Michael Hulet
47,913 PointsNo, it would not be an infinite loop without number++
. This is because you're checking how many objects are in the numbers
array, and break
ing based on that (not whatever the value of number
is). The reason your code isn't working with that line is because the ++
construct is not valid Ruby. While it's a feature of other languages that I like very much, Ruby doesn't implement it, and forces you to use the +=
construct, like this:
number += 1
Ricardo Hill-Henry
38,442 PointsRicardo Hill-Henry
38,442 PointsI'll have to stop posting things at 4am. Apparently I was focused on the items within the array, and disregarded the importance of the break statement nested within the if statement.
It also took me a while to realize the ++ construct wasn't supported in Ruby. It's surprising.