Reputation: 533
I have the code:
i = 1
while i < 11
do
end
print "#{i}"
i = i + 1
end
which causes an error "on line do: syntax error, unexpected keyword_do_block". If I move do
after the while
like this while i < 11 do
, the error goes away. It should not happen because do
is like an opening curly brace {
. Why is this an error?
Upvotes: 0
Views: 1043
Reputation: 1457
The keyword do is generally used for multiple lines, while {} are for one line code.
According to Ruby cookbook:
Keep in mind that the bracket syntax has a higher precedence than the do..end syntax. Consider the following two snippets of code:
More info at: Using do block vs braces {}
Upvotes: 0
Reputation: 16738
You actually have 2 issues here.
Here is the reference from the ruby doc http://ruby-doc.org/core-2.1.2/doc/syntax/control_expressions_rdoc.html
while Loop¶ ↑
The while loop executes while a condition is true:
a = 0
while a < 10 do
p a
a += 1
end
p a
Prints the numbers 0 through 10. The condition a < 10 is checked before the loop is entered, then the body executes, then the condition is checked again. When the condition results in false the loop is terminated.
The do keyword is optional. The following loop is equivalent to the loop above:
while a < 10
p a
a += 1
end
As to "why" this syntax was chosen you would need to ask the Matz, but I am not sure of the point of that question.
Upvotes: 0
Reputation: 75488
Because do
is only optional to while
that if you place it on a different line, it's already read as part of a different context:
while conditional [do]
code
end
Here, the while
statement is still valid and do
no longer connects to any that's why you see the error.
while conditional ## Parser validates this as complete.
do ## Parser sees this keyword as lost.
code
end
It's as if you did it without the while
block:
do ## Lost.
code
Which also produces the error syntax error, unexpected keyword_do_block
.
To clarify things more a bit, the while
syntax is not multi-line when trying to recognize the following do
. This may work:
while conditional do
code
end
And this one as well:
while conditional \
do
code
end
But the form in question wouldn't.
Upvotes: 7
Reputation: 4116
It should be:
$i = 0
while $i < 11 do
puts("Inside the loop i = #$i" )
$i +=1
end
Upvotes: 1