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
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:
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])