Skip to content

Instantly share code, notes, and snippets.

@dwaller
Created July 2, 2014 10:15
Show Gist options
  • Save dwaller/be47d790051ae43df367 to your computer and use it in GitHub Desktop.
Save dwaller/be47d790051ae43df367 to your computer and use it in GitHub Desktop.
SPA 2014 exercise
class Bottles
def song
verses(99, 0)
end
def verses(upper_bound, lower_bound)
upper_bound.downto(lower_bound).map { |i| verse(i) }.join("\n")
end
def verse(verse_number)
current_bn = create_bottle_number(verse_number)
next_bn = create_bottle_number(current_bn.next)
"#{current_bn.quantity.capitalize} #{current_bn.container} of beer on the wall, " +
"#{current_bn.quantity} #{current_bn.container} of beer.\n" +
"#{current_bn.action}, " +
"#{next_bn.quantity} #{next_bn.container} of beer on the wall.\n"
end
def create_bottle_number(number)
bottle_number_class = "BottleNumber#{number}"
if Object.const_defined? bottle_number_class
Object.const_get(bottle_number_class).new(number)
else
BottleNumber.new(number)
end
end
end
class BottleNumber
attr_reader :number
def initialize(number)
@number = number
end
def container
'bottles'
end
def pronoun
'one'
end
def quantity
number.to_s
end
def action
"Take #{pronoun} down and pass it around"
end
def next
number - 1
end
end
class BottleNumber0 < BottleNumber
def quantity
'no more'
end
def action
"Go to the store and buy some more"
end
def next
99
end
end
class BottleNumber1 < BottleNumber
def container
'bottle'
end
def pronoun
'it'
end
end
class BottleNumber6 < BottleNumber
def container
'six-pack'
end
def quantity
'1'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment