From: Ben Giddings Date: 2003-07-16T02:22:59+09:00 Subject: Re: How to reduce Ruby runtime error? On Tue July 15 2003 12:53 pm, Xiangrong Fang wrote: > if a[1].upcase == "GOOD" then... Then maybe you should say "if a[1].kind_of?(String) and "GOOD" == a[1].upcase" > a[1] is nil, and you can't do "upcase" with it! > > It is too tiring to find out all such possible errors, and raise > exceptions. Yes, but having your code blow an exception when you don't check the types is probably a much easier type of thing to debug and fix than the subtle bugs you can get when you change the behaviour of built-in classes. > > 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"? If you do this, then you begin to lose the distinction between nil and "" or 0. The handy thing with nil is that you can use it to provide an out-of-bounds value for certain operations. Say for example you have a server and you want to know how what the change in the number of users is: def getUsersDelta server.num_users - @previous_user_count end So you write code that uses this number, doing math on it, etc. Then later, you realize that unless the server is alive, the "num_users" accessor is meaningless so you change the function to do this: def getUsersDelta if server.isAlive server.num_users - @previous_user_count else nil end end If you modify nil to act like zero, then you have no way of knowing whether or not you have no change in the number of users, or whether the server has died. The other main reason not to change the definition of NilClass though is for ease of future maintenance. If somebody else, or you 5 years down the road, look at the code, you might forget that you modified NilClass in another file of the project. You may look at how you're dealing with values and assume that an exception will be thrown in a certain case but because you modified NilClass the error sneaks by. Ruby gives you more than enough rope to hang yourself, but keeps us suicide hotline people busy. :) Ben