From: Bob Gustafson Date: 2001-09-27T04:14:43+09:00 Subject: [ruby-talk:21745] inheritance Surprise! I had a problem with an object which, once it was created, would morph into an object of a different class, by calling a method within the original class. This was a surprise. This is not a very clear description, but consider the class and main program below. It describes a class of objects where the constructor (initialize, new..) is in the parent class (Time). This is not a problem, because created objects have the child class. (see the puts date_start.type) However, when the iterator - uptoByDay() is called, it uses an operator (+) which is implemented in the parent class. This creates a new object, but the type of the new object is the parent class rather than the child class. Why does the parent operator not work the same as the parent constructor and create an object of the child type? Surprise! To fix the problem, I created a method for + in the child class. You can test the improved action by removing the comments from the def +(n) method. I don't think I should have to create the def +(n) method. The iterator should produce results which are all of the child class. What do you think? BobG --------- code and run output below ---- [user1@hoho0 cron]$ cat date_bug.rb class MyDate < Time Day = 24*3600 # def +(n) # MyDate.at(super(n)) # end def uptoByDay(last) thumb = self while thumb <= last yield(thumb) # include first in range thumb += Day # increment by one day end end end # This is the main program.. year = 2000 date_start = MyDate.local(year,1,1) puts "The type of date_start is #{date_start.type}" date_end = MyDate.local(year,1,3) date_start.uptoByDay(date_end) do |myDate| puts "Here we are #{myDate.to_s} with type #{myDate.type}" end [user1@hoho0 cron]$ ruby date_bug.rb The type of date_start is MyDate Here we are Sat Jan 01 00:00:00 CST 2000 with type MyDate Here we are Sun Jan 02 00:00:00 CST 2000 with type Time Here we are Mon Jan 03 00:00:00 CST 2000 with type Time [user1@hoho0 cron]$