DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

99 Bottles Of Beer And A Meta Bottle

04.16.2005
| 2462 views |
  • submit to reddit
        module MetaBottle
  def self.make(x)
    Class.new do
      define_method(:bottle) do
        case x
        when 0 then "no more bottles"
        when 1 then "1 bottle"
        else        "#{x} bottles"
        end + " of beer"
      end
      define_method(:bottle_minus_one) do
        case x - 1
        when 0 then "no more bottles"
        when 1 then "1 bottle"
        else        "#{x} bottles"
        end + " of beer"
      end
      define_method(:to_s) do
        return <<T
#{bottle} on the wall, #{bottle},
take one down, pass it around,
#{bottle_minus_one} on the wall.\n
T
      end
    end
  end
end

(1..99).map { |x| MetaBottle.make(x) }.reverse_each do |bottle_class|
  bottle = bottle_class.new
  puts bottle
end