This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.

Managing Class Data
CodeExpectedActual
class Warning
  @@translations = { :en => 'Wet Floor',
                     :es => 'Piso Mojado' }
  def initialize(language=:en)
    @language = language
  end
  def warn
    @@translations[@language]
  end
end
Warning.new.warn
"Wet Floor" "Wet Floor"
Warning.new(:es).warn
"Piso Mojado" "Piso Mojado"
class Fate
  NAMES = ['Klotho', 'Atropos', 'Lachesis'].freeze
  @@number_instantiated = 0
  def initialize
    if @@number_instantiated >= NAMES.size
      raise ArgumentError, 'Sorry, there are only three Fates.'
    end 
    @name = NAMES[@@number_instantiated]
    @@number_instantiated += 1 
    puts "I give you... #{@name}!"
  end  
end
Fate.new
I give you... Klotho!
I give you... Klotho!
Fate.new
I give you... Atropos!
I give you... Atropos!
Fate.new
I give you... Lachesis!
I give you... Lachesis!
Fate.new
ArgumentError: Sorry, there are only three Fates.
...
ArgumentError: Sorry, there are only three Fates.
	from (irb):18:in `initialize'
	from (irb):28
class Module
  def class_attr_reader(*symbols)
    symbols.each do |symbol|
      self.class.send(:define_method, symbol) do
        class_variable_get("@@#{symbol}")
      end
    end
  end
  def class_attr_writer(*symbols)
    symbols.each do |symbol|
      self.class.send(:define_method, "#{symbol}=") do |value|
        class_variable_set("@@#{symbol}", value)
      end
    end
  end
  def class_attr_accessor(*symbols)
    class_attr_reader(*symbols)
    class_attr_writer(*symbols)
  end
end
Fate.number_instantiated
NoMethodError: undefined method `number_instantiated' for Fate:Class
...
NoMethodError: undefined method `number_instantiated' for Fate:Class
	from (irb):49
class Fate
  class_attr_reader :number_instantiated
end
Fate.number_instantiated
3 3