From: Daniel Schierbeck Date: 2006-08-08T07:30:10+09:00 Subject: Re: How to react on nil or wrong object-type as parameter Eric Hodel wrote: > On Aug 6, 2006, at 7:55 AM, Daniel Schierbeck wrote: > >> Yochen Gutmann wrote: >>> Hi, >>> I was just wondering: how do I react on a method-invocation with a >>> nil-object instead of eg. String? How do I test it? And how can I >>> assure that it is the right kind of object? >>> class AClass >>> def a_method aString >>> puts aString+aString >>> puts aString.reverse >>> end >>> end >>> an_object = AClass.new >>> an_object.a_method "hello" # works >>> an_object.a_method 3#-> undefined method >>> an_object.a_method nil #-> undefined method >> >> I'd do it like this: >> >> class SomeClass >> def foo(obj) >> str = obj.to_str > > Don't call to_str, call to_s. > >> puts str + str # or `str * 2' >> puts str.reverse >> end >> end >> >> Though I know some very smart people on this list disagree with me. > > Only because you call to_str. This is not the reason it exists. I favor using #to_str when I want to treat an object like a string. Practically all classes implement #to_s, so it's not really a type restriction. We're trying to solve two different problems -- I want to let the caller know if he sent the wrong kind of object as an argument. That's type checking. If you want to convert any object received to a string, then we're talking type conversion, which I think should be left to the caller in many cases. But that's just my humble opinion, of course. Cheers, Daniel