State Errors :: 0x40
Once again, a friend is preparing example programs for a blog post explaining how to handle error conditions in Ruby.
They send along a sample class for you to take a look at. It seems simple enough, as it's a variation on themes they've covered before.
class Bag
def initialize(size)
@size = size
@items = []
end
def <<(item)
raise "Bag is full!" unless @items.length < @size
@items << item
end
def count
@items.count
end
end
They also share a sample main program meant to demonstrate how the code works, which also seems fairly straightforward:
bag = Bag.new(3)
bag << "Apples"
bag << "Bananas"
bag << "Oranges"
p bag.count #=> 3
# this will raise an exception because the bag is full
bag << "Elephants"
Before you get a chance to properly review, they send a followup message wondering if they'd be better off simply giving the reader something concise to run which adds all the items at once, skipping the printout of the bag.count
:
Bag.new(3) << "Apples" << "Bananas" << "Oranges" << "Elephants"
You give that some thought, but then realize upon closer reading of the Bag
class definition that this isn't going to work as your friend expects it to.
In fact, it won't raise an error at all!
(1) What causes this code to bypass the raise "Bag is full"
guard, and how can it be fixed?
You can preorder now to be among the first to gain access when it is released.