Syntax Errors :: 0x03
At first glance, nothing looks weird about how the following program is colorized.
But continuing on a theme, a botched auto-completion on a single line of its code has broken things in a way that will cause it to crash before it ever gets a chance to run:
class Bag
def initialize
@items = []
end
def add_item(item)
@items.push(item)
else
def take_item
@items.shuffle!
@items.pop
end
end
bag = Bag.new
bag.add_item("cranberries")
bag.add_item("stuffing")
bag.add_item("turkey")
p bag.take_item
(1) Where is the broken line of code and how would you fix it?
# [ANSWER 1] #
The `add_item` method is missing an `end` keyword, which was accidentally
written as `else` instead.
(2) If this code is run as-is, Ruby will report both the problematic line that needs fixing, as well as another syntax error elsewhere in the code. What causes that to happen?
# [ANSWER 2] #
Ruby does not stop trying to parse the method definition for `add_item`
when it hits the line with the `else` keyword on it, but instead
keeps going as if the `take_item` method definition had been nested inside it.
This makes it so that the end that was meant to close the `Bag` class
definition is treated as if it is the end of the `add_item` method instead,
and all the code that follows is still inside the `Bag` class definition.
So in addition to the error about the misplaced `else` keyword, you end up
getting an error that the parser reached the end of the file without finding
an `end` for the `Bag` class definition.
Hint: Understanding what the
Bag
object is and how it is used in this example program *won't*
help you answer these questions. However, if you focus on reading the code one
color at a time rather than one line at a time, the bug will likely jump straight out at you.
Related Notes :: 0xF003