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 trialfrontend
15,619 Pointsruby question on 'end'
in the following statement...
numbers = []
number = 0
loop do
if numbers.count >= 3
break
end
numbers.push(number)
number += 1
end
why do you need to 'end' . why can't you just use one end at the end of the scope? i am confused...please help.
1 Answer
Jon Dalberg
6,788 PointsThe "if" statement needs to know where it stops and that is determined by the "end" keyword. You could have written it to be in one line like this:
break if numbers.count >= 3
That would avoid having another "end" keyword. Some prefer this way when the action to execute is small (like just a "break" statement in your example).
frontend
15,619 PointsThanks Jon....the syntax is still a bit fuzzy since I initially learned javascript. it seems a bit inefficient to have two ends there whether or not i put the break on one line. the break statement determined when the loop stops, not the if statement. that is why it is confusing to put multiple ends in one function.
Jason Anello
Courses Plus Student 94,610 PointsThis isn't all that different from what you would have in javascript.
There would be an opening and closing curly brace for the if
block and opening and closing curly braces for the loop.
The 2 closing curly braces in js }
would be equivalent to the 2 end statements in the ruby code.
I assume your question is asking about why the first end is necessary.
As Jon already mentioned, you have to know where it ends. Without it, does the numbers.push
line belong to the if
or the loop? There's no way to know.
Python eliminates the need for both curly braces and end statements but it still has to deal with this problem of where blocks end. Python handles it with indentation.
In all 3 languages, you have to know where the if ends, but they each handle it with different syntax.
frontend
15,619 Pointsfrontend
15,619 PointsThanks Jason. It seems mind boggling how many languages & frameworks are out there which seemingly all accomplish the same thing. Wouldn't it be beautiful if there was one language that accomplished everything? It almost seems like they make it confusing on purpose. One day there will be a programming language that is way more efficient and readable than the ones we know today.