From: "Hal E. Fulton" Date: 2003-07-16T01:20:49+09:00 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