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 Instance Data
CodeExpectedActual
class Frog
  def initialize(name)
    @name = name    
  end
  def speak
    # It's a well-known fact that only frogs with long names start out
    # speaking English.
    @speaks_english ||= @name.size > 6
    @speaks_english ? "Hi. I'm #{@name}, the talking frog." : 'Ribbit.'
  end
end
Frog.new('Leonard').speak
"Hi. I'm Leonard, the talking frog." "Hi. I'm Leonard, the talking frog."
lucas = Frog.new('Lucas')
lucas.speak
"Ribbit." "Ribbit."
lucas.name
NoMethodError: undefined method `name' for #<Frog:0xb7d0327c  @speaks_english=true, @name="Lucas">
Error! (Exception?) Here's stdout:
NoMethodError: undefined method `name' for #<Frog:0xb7c2ad68 @name="Lucas", @speaks_english=false>
	from (irb):15
class Frog
  attr_reader :name
end
lucas.name
"Lucas" "Lucas"
lucas.speaks_english = false
NoMethodError: undefined method `speaks_english=' for #<Frog:0xb7d0327c @speaks_english=false, @name="Lucas">
Error! (Exception?) Here's stdout:
NoMethodError: undefined method `speaks_english=' for #<Frog:0xb7c2ad68 @name="Lucas", @speaks_english=false>
	from (irb):20
class Frog
  attr_accessor :speaks_english
end
lucas.speaks_english = true
lucas.speak
"Hi. I'm Lucas, the talking frog." "Hi. I'm Lucas, the talking frog."
class Frog
  def speaks_english
    @speaks_english
  end
  def speaks_english=(value)
    @speaks_english = value
  end
end
michael = Frog.new("Michael")
#<Frog:0xb7cf14c8 @name="Michael"> #<Frog:0xb7c135a0 @name="Michael">
michael.speak
"Hi. I'm Michael, the talking frog." "Hi. I'm Michael, the talking frog."
michael
#<Frog:0xb7cf14c8 @name="Michael", @speaks_english=true> #<Frog:0xb7c135a0 @name="Michael", @speaks_english=true>
michael.instance_variable_get("@name")
"Michael" "Michael"
michael.instance_variable_set("@name", 'Bob')
michael.name
"Bob" "Bob"
class Frog
  define_method(:scientific_name) do 
    species = 'vulgaris'
    species = 'loquacious' if instance_variable_get('@speaks_english')
    "Rana #{species}"
  end
end
michael.scientific_name
"Rana loquacious" "Rana loquacious"