From: daz Date: 2004-08-26T14:30:42+09:00 Subject: Re: Inheritance from built-in class Nicolaj Soendberg-Madsen wrote: > I have a question regarding inheritance from built-in classes. To simplify > it, say I want to create a time-stamped array, which is an array with a > time-stamp. Then I want to override the to_s method. I tried the following > code: > > > class Time_stamped_array < Array > def initialize > @time_stamp = Time.now > end > > def to_s > super + " #{@time_stamp}" > end > > end > > ta = Time_stamped_array.new > > puts ta.to_s > > > However this last call seems to invoke to_s in the super class (Array) > and not in my new class. How do I do what I intented to do instead? > Isn't it possible to override built-in methods? > That should be working, but your Time_stamped_array is empty so only the date appears, I guess (?) class Time_stamped_array < Array def to_s super + " #{Time.now}" end end ta = Time_stamped_array.new ta.push('ab') # add to Time_stamped_array ta.push('cd') # - another - p ta #-> ["ab", "cd"] puts ta.to_s #-> abcd Thu Aug 26 09:10:11 ... :daz