From: Eric Hodel Date: 2006-08-09T07:19:55+09:00 Subject: Re: How to react on nil or wrong object-type as parameter On Aug 8, 2006, at 12:45 PM, Daniel Schierbeck wrote: > Eric Hodel wrote: >> On Aug 8, 2006, at 10:35 AM, Daniel Schierbeck wrote: >>> Eric Hodel wrote: >>>> A Name is not a String. You don't #each it, you don't #chop it, >>>> its never #empty?, ... >>> >>> That's why you use the return value of #to_str. >> You don't call #to_str, String calls #to_str when it needs to. > > So the implementation of e.g. String#+ is wrong? Or is it okay for > a method on String to call #to_str on its arguments? I suggest you read through the archives to discover when to use #to_str and when to use #to_s. I've linked to matz' discussion of the matter several times. The short version is, if you call #to_str or implement #to_str you are probably doing something wrong. >>> I'm not saying this is how everybody should do it, I'm just >>> saying that it's a very smart way to handle types -- duck typing >>> being a very similar way. >> It isn't a smart way to handle types, it is a broken and wrong way >> to handle types. > > I'm sorry, but I have to disagree. Read the RomanNumeral example > again -- it's an integer, but it doesn't inherit from Integer. Numeric duck types use #coerce because #to_int won't cover all the bases. See the earlier thread on #to_i vs #to_int, and try: 5 + Roman.new(6) You'll find that #to_int does not do anything for you. This is why you shouldn't call or define #to_xxx methods, how and where they are supposed to be used is confusing, convoluted and error- prone. They aren't supposed to be used where you think they are supposed to be used. PS: I can't think of a legitimate reason to define a RomanNumeral class. It would be easier to add Integer#to_roman that returns a String and Kernel#Roman that parses a String into an Integer. For bonus points, define #const_missing to parse a constant that is also a Roman numeral. -- Eric Hodel - drbrain@segment7.net - http://blog.segment7.net This implementation is HODEL-HASH-9600 compliant http://trackmap.robotcoop.com