From: Brad Date: 2004-01-01T00:16:47+09:00 Subject: Re: Overriding to_s ts wrote: > >>>>> "B" == Brad writes: > > B> Is there a way to override the to_s method such that it takes a > B> parameter? For example, if I wanted to provide a format specifier > B> for a number: > > well, you have several problems > > B> class Numeric > > #to_s is defined in Integer, Float, Bignum, ... not in Numeric > > If you define it in Numeric, ruby will use the old definition in > Integer, ... > > B> def to_s(optFormat) > > you are saying that #to_s must have a parameter, this mean that you can't > call it 12.to_s > > Perhaps best to write it > > def to_s(optFormat = nil) > > now Integer#to_s can take an optional argument, this mean that your new > method #to_s is not really adapted for Integer (except if format_number > take this in count) > > B> if !optFormat.nil? > B> # format a string based on the optFormat format > B> # specifier. > B> retVal = format_number(self,optFormat) > B> else > B> retVal = self.to_s > > here, you call recursively #to_s. > > Perhaps best to alias #to_s before redefining it, and call the alias > > B> end > B> retVal > B> end > B> end > > > Guy Decoux > > > > Guy: Thanks for the speedy response! I guess I was being a bit naive, I thought Numeric was a base class for Integer, Float, etc. Is there any way to redefine to_s across the board, i.e. for Integer, Float, etc without having to duplicate code for each numeric type? Yeah, the code is pretty shabby :,. I didn't put much thought into it as it was only meant to be an illustration. Don't get me wrong though you're points are very good and obviously are not part of my native ruby thinking, otherwise the sample would have included them. Thank you. :) Hopefully I don't sound rude. :/ Regards, Brad