From: Robert Klemme Date: 2006-08-09T17:25:18+09:00 Subject: Re: How to react on nil or wrong object-type as parameter I sort of agree to both of you and I think despite this thread you maybe not too far away from each other. On 09.08.2006 00:19, Eric Hodel wrote: > 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. But *if* you define a class Roman #to_int should be part of it because a roman can actually be treated as an integer. Of course you'll also have to implement #coerce and probably several others. > 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. I agree that implementing and invoking #to_int and #to_str needs considerably more consideration than their counterparts #to_i and #to_s - and you'll rarely see them implemented. The standard lib has several classes which define these methods: you can try it out: ruby -e '%w{to_int to_str}.each {|mn| print "\nMethod ", mn, ":\n"; ObjectSpace.each_object(Module) {|cl| p cl if cl.instance _methods.any? {|m| mn == m}}}' > 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. IMHO you can take at least two different positions here - which one is more appropriate probably depends on the problem to solve. You can view a roman number as another representation of an integer value. In that case Erik's approach is more appropriate. You can as well view a roman number as something specific if it has properties that are not covered by standard integer classes. In that case it deserves a class of its own including #to_i, #to_int, #coerce, #eql?, #==, #hash, #<=>, #to_s and maybe more. Kind regards robert