Skip to content

Instantly share code, notes, and snippets.

@psparrow
Last active February 18, 2017 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psparrow/d2ea96935297f0dbde2f7a1139733487 to your computer and use it in GitHub Desktop.
Save psparrow/d2ea96935297f0dbde2f7a1139733487 to your computer and use it in GitHub Desktop.
My 99 Bottles solution with refactoring, memoization, and six-pack feature
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