R
Robert Klemme
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
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