From: Brian Candler Date: 2003-07-16T02:39:34+09:00 Subject: Re: How to reduce Ruby runtime error? On Wed, Jul 16, 2003 at 01:53:12AM +0900, Xiangrong Fang wrote: > Hi Hal, > > Thank you for the suggestions. The last thing I want to do is to raise > exceptions! If I raised exception, the program is broken. I will have to > deal with that manually. > > Let me give you an example. I have a input line: > > line = "a b" > > I used a=line.split(" "), it becomes a=["a", "b"], that's what I want. > However, in real environment, some time the input is: > > line = "c" > > then, a=["c"]. In this case, if my program write somethin like > > if a[1].upcase == "GOOD" then... > > a[1] is nil, and you can't do "upcase" with it! If you know in advance that a[1] might not exist, then you can write your code as if a[1].to_s.upcase == "GOOD" then ... This also works if a[1] is some object other than a string (e.g. a number). You will get some sort of string from it. But Ruby is trying to tell you that it doesn't make sense to compare "no object" with a string. So perhaps your code can be cleaned up: e.g. next unless a[1] # skip this loop iteration unless we have an item if a[1] and a[1].upcase == "GOOD" then... > Actually, your "Not Recommended" ideas is better for me: > > > Not recommended: You could convert a nil value on entry > > into the method: > > > > x = [] if x.nil? Or even simpler: x ||= "foo" This is a very common Ruby idiom for "set a default value" > > 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 want my program to be robust. So the above recommendation is a good > idea. I don't know why it is "not recommended"? Well, it wouldn't work in your case, because you have not defined a 'downcase' method in NilClass. > Is it possible to "overload" the Nil class so that it is polymophic? for > example, > > if the method upcase is called, nil act like string, if the expression > a = 2 + nil is executed, nil act like zero? That will be fantastic. You can, but you have to write it yourself by tediously adding all the appropriate methods to NilClass, Fixnum, String etc. This is because operators belong to classes: a+b calls a.+(b), so 2+nil calls Fixnum#+, whereas nil+2 calls NilClass#+. You'll then have code which pollutes the core Ruby classes, which is probably not a good thing (especially if you end up running your code on a shared interpreter, e.g. under mod_ruby) Regards, Brian.