From: daz Date: 2003-07-16T14:45:12+09:00 Subject: Re: How to reduce Ruby runtime error? "Xiangrong Fang" wrote: > > if a[1].upcase == "GOOD" then... > > a[1] is nil, and you can't do "upcase" with it! > I'd use (a[1] ||'').upcase ||'' over 'to_s' ||0 over 'to_i' etc., to handle nil values. > > 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. > That would be _different_. I wouldn't do it, even in the privacy of my own home :) irb(main):001:0> dat = [3, 4, nil] => [3, 4, nil] irb(main):002:0> dat.map {|z| z + 1} NoMethodError: undefined method `+' for nil:NilClass irb(main):003:0> dat.map {|z| (z ||0) + 1} => [4, 5, 1] irb(main):004:0> dat = ['three', 'four', nil] => ["three", "four", nil] irb(main):005:0> dat.map {|z| z + '*'} NoMethodError: undefined method `+' for nil:NilClass irb(main):006:0> dat.map {|z| (z ||'') + '*'} => ["three*", "four*", "*"] daz