From: Phrogz Date: 2007-11-11T12:45:03+09:00 Subject: Re: composition (Dragon "has a" Trait) Thufir wrote: > C:\code\creat3>type Creature.rb > class Creature ... > def initialize () > @location = Room.new > @traits = Traits.new > end ... > end ... > class Dragon < Creature > def initialize () > @traits.life = 1340 > end > end It seems you think that the initialize of Creature gets called because Dragon is a subclass of it. This is not the case. For example: irb(main):001:0> class Foo irb(main):002:1> def initialize irb(main):003:2> p "Foo.initialize" irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> Foo.new "Foo.initialize" irb(main):007:0> class Bar < Foo irb(main):008:1> def initialize irb(main):009:2> p "Bar.initialize" irb(main):010:2> end irb(main):011:1> end => nil irb(main):012:0> Bar.new "Bar.initialize" If you want the initialize method from a superclass to be called, you need to explicitly do so, and decide when to do it. For example: irb(main):019:0> class Bar2 < Foo irb(main):020:1> def initialize irb(main):021:2> super # call this first irb(main):022:2> p "Bar2.initialize" irb(main):023:2> end irb(main):024:1> end => nil irb(main):025:0> Bar2.new "Foo.initialize" "Bar2.initialize" Though it doesn't make a difference in my above simple example, note that calling "super" without any parentheses automatically passes in any arguments passed to the initialize function. This is convenient, but can be a problem if your superclass's initialize method expects different arguments than the subclass's.