On Tue, Jun 24, 2003 at 04:45:05AM +0900, Ryan Pavlik wrote: > A number of us desire a more standard, more scalable type conversion > mechanism. By "type conversion", I mean you've got one thing (say, an > Integer), and you want it to be another (say, a String). > > Currently we do this: > > x = 42 > s = x.to_s > > The problem is this is both a loose convention and it doesn't scale well > at all. A case-in-point of the former: > > x = nil > s = "" > s << x > > => TypeError: cannot convert nil into String > > Yet, there's a NilClass#to_s... but this looks for NilClass#to_str. > There's not even internal consistency. It is consistent: - to_int, to_str, to_ary are called implicitly - to_i, to_s, to_a are called explicitly In other words, if an operator decides to do an automatic cast of one of its operands, it calls the long version. If you want to force a conversion yourself, you use the short version. This is done because there is loss of data in the second case, and allowing automatic conversion would hide bugs which would be very hard to detect. For example, the value 'nil' is *not* the same as an empty string. If I do mystr << myval where myval is 'nil' then in general I want it to raise an exception, because 'nil' is not a string, so I probably forgot to initialise it. However, if I *know* that myval may contain nil, and want it treated as an empty string, then I do mystr << myval.to_s The same applies for strings containing numeric values, and vice versa. a = "1" b = 2 c = a + b # String "12" ? Fixnum 3? or something else? What should c contain? The answer is 'it depends'. Ruby can't know what your intention is, so it fails. You tell it what you want by using either 'to_s' or 'to_i' to convert Your solution, a.as(Fixnum) + b.as(Fixnum), seems to me to be the same as a.to_i + b.to_i, but more verbose and less efficient. > This leads us to the second > point; it doesn't scale. In order to provide a conversion from each > type to another, it requires (type^2) methods in each class. Sure, but in the general case it does not make sense to attempt to convert type X to type Y. Object X has instance variables @a,@b,@c and Object Y has instance variables @d, @e; how are you going to convert an instance of X into an instance of Y? It probably makes sense for most objects to have a 'printable' form of their contents for display purposes - hence X.to_s - and also a detailled printable version for debugging, hence X.inspect. But I don't see any need for generic 'X to Y'. Regards, Brian.