From: "John W. Long" Date: 2003-07-16T01:43:45+09:00 Subject: Re: How to reduce Ruby runtime error? Actually I consider it better not to check the type. You should get used to looking at the stack trace to see what is wrong. Generally you'll get some kind of method missing error. Then you puts the type of the object being passed in, run your tests again, and check the type. I think about it this way: if the object passed in implements the correct interface then it should be allowed to be passed in, regardless of whether it is an instance_of? or kind_of? a certain object. If you need to prevent a certain kind of class from being passed in (such as the Nil class in your example) check for it at the beginning of your method like so: raise "cannot accept nil argument" if object.nil? I would consider it preferable to exclude based on type rather than include based on type. -- John Long > -----Original Message----- > From: Hal E. Fulton [mailto:hal9000@hypermetrics.com] > Sent: Tuesday, July 15, 2003 11:21 AM > To: ruby-talk ML > Subject: Re: How to reduce Ruby runtime error? > > > ----- Original Message ----- > From: "Xiangrong Fang" > To: "ruby-talk ML" > Sent: Tuesday, July 15, 2003 11:05 AM > Subject: How to reduce Ruby runtime error? > > > > Hi my friends, > > > > I am thinking of how can I reduce Ruby runtime error. Not like > > languages such as C or Pascal, Ruby is typeless. This is a > good thing, > > especially in design time. However, I found that my > application is not > > stable due to this feature. > > > > For example, a routine is expecting a string, and this > string turned out > > to be nil at runtime, an error occurred. In Delphi, for > example, it is > > impossible that a string becomes a nil, it will be an empty string. > > > > How can I better utilize Ruby's typeless feature yet avoid > such anonying > > runtime problem? > > You can always check types explicitly if you > really want to: > > raise "Expecting an array" if not x.is_a? Array > > Or you could test for nil: > > raise "Argument was nil" if x.nil? > > You can test for methods available ("duck typing") > rather than actual class: > > raise "Object has no 'push' method" if not x.respond_to? :push > > You can check for the "magic" conversion methods such as > to_str and to_ary: > > if not x.is_a? String > x = x.to_str if x.respond_to? :to_str > else > raise "Wanted a string" > end > > Not recommended: You could convert a nil value on entry > into the method: > > x = [] if x.nil? > > Not recommended: You could modify the NilClass so that a > nil value acted the way you want: > > class NilClass > def +(value) > value # nil + x always equals x > end > end > > I'm sure there are other ways. > > Hal > > -- > Hal Fulton > hal9000@hypermetrics.com > > > > >