Voting

Category

real language

Bookmarking

Del.icio.us Digg Diigo DZone Earthlink Google Kick.ie
Windows Live LookLater Ma.gnolia Reddit Rojo StumbleUpon Technorati

Language Ruby

(wall-based OO version)

Date:07/07/05
Author:Kevin Baird
URL:n/a
Comments:2
Info:http://ruby-lang.org
Score: (2.95 in 19 votes)
#!/usr/bin/env ruby
# 99 bottles problem in Ruby

class Wall

  def initialize(num_of_bottles)
    @bottles = num_of_bottles
  end

  def sing_1_verse
    @output = sing_num(@bottles) + " on the wall, " + sing_num(@bottles) + "\n"
    @output += "take one down, pass it around, " + sing_num(@bottles-1) + "\n\n"
    return @output
  end

  def sing_all
    @output = ''
    while @bottles > 0 do
      @output += sing_1_verse()
      @bottles -= 1
    end
    return @output
  end
  
  def sing_num(num)
    @counter = (num > 1) ? 'bottles' : 'bottle'
    "#{num} #{@counter} of beer"
  end

end # class Wall

wall = Wall.new(99)
puts wall.sing_all()

Download Source | Write Comment

Alternative Versions

VersionAuthorDateCommentsRate
Using continuations, singleton classesVictor Borja09/15/069
alternative versionGreg T.05/18/0510
minimal versionAnonymous05/18/053
shows inheritance, iterators, yield, etcKian Wright06/10/050
In wordsDaniel Straight07/10/061
object-oriented versionMike Gertz04/20/052
monkeypatch and anonymous procsJ. B. Rainsberger04/04/070
Readably re-opening Integer, teetotallerEric Budd01/06/080

Comments

>>  AEDE said on 10/28/05 14:51:31

AEDE smart but not very ruby oriented...
looks like C++ to me...

>>  Brad said on 03/08/08 22:16:30

Brad This looks very clean to me. I'm looking for an easy to grok scripting language and something that slides into OO this easy is to be commended. It doesn't look like C++ to me (nor Java for that matter.) It looks a bit easier/simpler than trying the same in Python.

This has been an extremely useful example to me.

Download Source | Write Comment

Add Comment

Please provide a value for the fields Name, Comment and Security Code.
This is a gravatar-friendly website.
E-mail addresses will never be shown.
Enter your e-mail address to use your gravatar.

Please don't post large portions of code here! Use the form to submit new examples or updates instead!

Name:

eMail:

URL:

Security Code:
  
Comment: