From: cies Date: 2006-10-24T11:20:27+09:00 Subject: Re: Override Time#to_s -- how? > > I'd like to override the Time#to_s function to parse Time objects a > > specific way -- how can I do this from within my script? (Without > > modifying the Time class itself) or maybe you want: irb(main):001:0> class MyTime < Time irb(main):002:1> def to_s irb(main):003:2> "time from MyTime" irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> MyTime.new.to_s then the Time class is guaranteedly not changed in behavior by the above code... cies breijs. On 10/24/06, Wilson Bilkovich wrote: > On 10/23/06, Ben Winekur wrote: > > Hey everyone, > > > > I'd like to override the Time#to_s function to parse Time objects a > > specific way -- how can I do this from within my script? (Without > > modifying the Time class itself) > > > > Thanks, > > Ben > > > > What do you mean by 'without modifying the Time class itself'? Isn't > that precisely what you want to do? > > All classes are 'open' in Ruby, so you can simply do: > > class Time > def to_s > "blah" > end > end > > If you need access to the original method as well, you can do this: > > class Time > alias_method :original_to_s, :to_s > def to_s > "The old to_s method would have said: " + self.original_to_s > end > end > > -- "Computer games don't affect kids; I mean if Pac-Man affected us as kids, we'd all be running around in darkened rooms, munching magic pills and listening to repetitive electronic music." -- Kristian Wilson (Nintendo, Inc), 1989