From: Daniel Schierbeck Date: 2006-08-07T03:50:12+09:00 Subject: Re: How to react on nil or wrong object-type as parameter Yochen Gutmann wrote: >> def foo(obj) >> unless obj.respond_to? :to_str >> raise ArgumentError, "argument must be a string" >> end >> >> str = obj.to_str >> >> ... >> end > I see, but if it is a long method I might end up with > > unless obj.respond_to? :to_str,:another_method, :yet_another_method, > :and_again_another_method Yes, that's true. But then again, all objects that respond to those messages can be used as arguments to your method, thus increasing the flexibility of your application dramatically. Oftentimes, it isn't necessary to use #respond_to?. Simply call the methods on the received argument -- if an exception is raised, you can easily debug. e.g. nil.foo => test.rb:11: undefined method `foo' for nil:NilClass (NoMethodError) Here you get the line number the error occurred on (11), the kind of exception raised (NoMethodError), the message not responded to (#foo), and what kind of object the message was sent to (nil). > Another way would be to wrap a begin/rescue around the whole method-body > to capture all possibly arrising ArgumentErrors. Am I right with this? You could do it like this: def foo(obj) foo.bar! rescue NoMethodError => error puts "argument must respond to #{error.name}" end Although this has the downside that it'll rescue *all* such exceptions, even those caused by your own mistakes. Cheers, Daniel