
Justin Sze Wei Teo
9,418 PointsQuestion on "break loop at 3 items in array" Challenge
Hi guys,
Why is it that when I use numbers.length = 3, as opposed to numbers.length >=3 in the if statement, it doesn't work?
Shouldn't it also work as well, since the moment the no. of array items hits the equivalent of 3, it will break the loop?
That is, why doesn't the following work?
numbers = []
number = 0
loop do
numbers.push(number)
number + 1
if numbers.length = 3
break
end
end

Jason Anello
Pro Student 94,552 PointsTagging Jay McGavren
The tester might not be testing if the correct numbers are being added to the array.
2 Answers

Jason Anello
Pro Student 94,552 PointsHi Justin,
You're using a single equal sign there so it's trying to do an assignment rather than an equality comparison.
Switch to ==
Also, you're not changing the value of number
. You're adding 1 to it but you're not assigning that back to number
You can do
number = number + 1
# or
number += 1
Either of those will add 1 to the current value of number
and store the result back into number
Your existing code is continually pushing 0 onto the array which I don't think should be passing.

Justin Sze Wei Teo
9,418 PointsHi Jason,
Thanks for the swift response. Apologies I mis-typed my earlier code.
I did mean to type,
numbers = []
number = 0
loop do
numbers.push(number)
number += 1
if numbers.length = 3
break
end
end
The above doesn't pass this challenge. Have i misinterpreted the question "Use the break keyword to exit the loop once the numbers array has 3 items." ?
Kindly advise, thanks

Jason Anello
Pro Student 94,552 PointsYou still have a single equal sign. I mentioned that you have to switch it to a double equal sign to do equality comparison.
Right now you're trying to assign 3 to numbers.length but you want to know if they're equal.
if numbers.length == 3

Jay McGavren
Treehouse TeacherGood answer Jason Anello . I've confirmed that the challenge will pass once the submission is fixed.

Justin Sze Wei Teo
9,418 PointsOh Wow it works now, I finally got what you meant Jason. Thanks!
Jason Anello
Pro Student 94,552 PointsJason Anello
Pro Student 94,552 Pointsfixed code formatting