Dealing with nil

Hi,

we had frequent discussions about how to make code safely deal with
possible nil values. I remember having seen various solutions
proposed. However, I cannot remember having seen this, which just
occurred to me:

class Object
def nil_safe(fallback = self, &b)
if nil?
fallback
else
instance_eval(&b)
end
end
end

With this, you can do

irb(main):038:0> s=nil
=> nil
irb(main):039:0> s.nil_safe(0) {length}
=> 0
irb(main):040:0> s=“foo”
=> “foo”
irb(main):041:0> s.nil_safe(0) {length}
=> 3

Admittedly this is not very pretty.

An alternative definition would be

class Object
def nil_safe(fallback = self, &b)
if nil?
fallback
else
yield self
end
end
end

And then

irb(main):051:0> s=nil
=> nil
irb(main):052:0> s.nil_safe(0) {|x| x.length}
=> 0
irb(main):053:0> s=“foo”
=> “foo”
irb(main):054:0> s.nil_safe(0) {|x| x.length}
=> 3

What do others think?

Kind regards

robert

With this, you can do

irb(main):038:0> s=nil
=> nil
irb(main):039:0> s.nil_safe(0) {length}
=> 0

I don’t really get your example…

Why not just use s.to_s.length?

In the more general case, why no just follow the pattern s.nil? ? 0 :
s.length?

On Mon, Mar 3, 2008 at 10:38 AM, Robert K.
[email protected] wrote:

Hi,

we had frequent discussions about how to make code safely deal with
possible nil values. I remember having seen various solutions
proposed. However, I cannot remember having seen this, which just
occurred to me:

Raganwald proposed Object#andand and Object#me
http://weblog.raganwald.com/2008/01/objectandand-objectme-in-ruby.html

He also discusses Object#if_not_nil
http://weblog.raganwald.com/2008/02/ifnotnil.html
which was proposed by François Beausoleil at
http://blog.teksol.info/2007/11/23/a-little-smalltalk-in-ruby-if_nil-and-if_not_nil

On Mon, Mar 3, 2008 at 1:10 PM, ThoML [email protected] wrote:

Is there really an advantage over the more “traditional” solutions:

I think it is more readable and you can chain additional method calls

Vendors.find(“location = ‘Worms’”).andand.products.find_all

On 03.03.2008 11:20, Thomas W. wrote:

He also discusses Object#if_not_nil
if_not_nil?
which was proposed by François Beausoleil at
http://blog.teksol.info/2007/11/23/a-little-smalltalk-in-ruby-if_nil-and-if_not_nil

Ah, good point! Thanks for the links. I guess that solution is just
too obvious - I just could not remember having seen it. I have to take
my Voltax… :wink:

Kind regards

robert

Is there really an advantage over the more “traditional” solutions:

x && x.foo
x.foo if x
x || 1
x ? x.foo : 1
x && x.foo || 1

Apart from that I think one should rather deal with nils explicitly
(and maybe a little bit earlier than in your examples).

BTW I personally would rather prefer a statement that throws an error
if an unchecked nil is assigned to a variable. (Which isn’t too
difficult to do.[1])

Regards,
Thomas.

[1] http://groups.google.com/group/comp.lang.ruby/msg/9fe1b629764a196a