Last active
February 18, 2017 19:41
-
-
Save psparrow/d2ea96935297f0dbde2f7a1139733487 to your computer and use it in GitHub Desktop.
My 99 Bottles solution with refactoring, memoization, and six-pack feature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Bottles | |
def song | |
verses 99, 0 | |
end | |
def verses high, low | |
high.downto(low).map { |count| verse count }.join "\n" | |
end | |
def verse count | |
"#{container(count).capitalize} of beer on the wall, "\ | |
"#{container(count)} of beer.\n"\ | |
"#{action(count)}, #{container(successor(count))} of beer on the wall.\n" | |
end | |
private | |
def container count | |
unless @containers | |
@containers = Hash.new { |hash, key| "#{key} bottles" } | |
@containers[6] = '1 six-pack' | |
@containers[1] = '1 bottle' | |
@containers[0] = 'no more bottles' | |
end | |
@containers[count] | |
end | |
def action count | |
unless @actions | |
@actions = Hash.new 'Take one down and pass it around' | |
@actions[1] = 'Take it down and pass it around' | |
@actions[0] = 'Go to the store and buy some more' | |
end | |
@actions[count] | |
end | |
def successor count | |
count > 0 ? count - 1 : 99 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment