The Ruby Programming Language

Class Variables

class Song
  attr_reader :name # If it starts with : then its a symbol
  attr_writer :name, :artist

  @@plays = 0  # Class variables start with @@

  # The constructor:
  def initialize(name, artist, duration)
    @name = name
    @artist = artist 
    @duration = duration
  end

  def to_s
    "Song: #@name--#@artist (#@duration)" #perl-like replacement, no return.
  end

  def Song.maxLength # Class methods start with the class name
    5000
  end
end

song = Song.new("Re: Your Brains", "Jonathan Coulton", 272)

puts song #Song: Re: Your Brains--Jonathan Coulton (272)

song.artist = "Me" # This fails! by default they are private.

puts song #Song: Re: Your Brains--Me (272)

puts Song.maxLength # 5000

José M. Vidal .

5 of 11