On page 194 of the book _Ruby Wizardry_, by Eric Weinstein, the
following function appears:
def attack
puts "Did #{rand(strength)} damage!"
end
According to the text, this function should exhibit the following
behavior in irb:
>> rex = GuardDog.new('Rex', 7)
=> #<GuardDog:0x0000010334e168 @strength=7, @name="Rex">
>> rex.attack
Did 1 damage!
=> nil
>> rex.attack
Did 4 damage!
=> nil
However, instead, rex.attack exhibits the following behavior:
>> irb(main):006:0> rex.attack
>> Did #{@damage} damage!
>> => nil
The complete code for my guard_dog.rb file, which contains the
relevant functions, is as follows:
class Animal
attr_accessor :name
def initialize(name, legs=4)
@name = name
@legs = legs
end
end
class Dog < Animal
attr_accessor :name
def initialize(name)
@name = name
end
def bark
puts 'Arf!'
end
end
class GuardDog < Dog
attr_accessor :strength
def initialize(name, strength)
@strength = strength
super(name)
end
def bark
puts 'Stop, in the name of the law!'
end
def attack
@damage = rand(@strength)
puts 'Did #{@damage} damage!'
end
end
Why doesn't rex.attack exhibit the desired behavior?
--
Benjamin L. Russell / DekuDekuplex at Yahoo dot com
http://dekudekuplex.wordpress.com/
Computer Science Document Proofreader/Editor
"Furuike ya, kawazu tobikomu mizu no oto." -- Matsuo Basho^