I'm trying to follow along with a lecture by implementing a gumball machine as a state machine. The intent is that it's initialized with 0 coins and 10 gumballs. By default, it's ready; you insert a coin, and from there either request_refund or turn_crank. Turning the crank will increment the coin counter by one while decrementing the coin counter (and returning a random gumball colour). If there are 0 gumballs left then turning the crank does nothing.
class GumballMachine
attr_reader :coins, :gumballs
def initialize
@coins = 0
@gumballs = 10
super
end
def dispense_gumball
@coins += 1
@gumballs -= 1
[:red, :green, :blue, :purple, :pink].sample
end
state_machine :state, initial: :ready do
event :insert_coin { transition :ready => :holding_coin }
event :request_refund { transition :holding_coin => :ready }
event :turn_crank do
dispense_gumball if @gumballs > 0
transition :holding_coin => :ready
end
end
end
This fails, though, on the statement if @gumballs > 0
, because @gumballs
hasn't been defined at that point. I've read the documentation back and forth and Googled the hell out of it but I have zero idea what's wrong with this or what I should be doing instead.