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
On Mon, Mar 3, 2008 at 10:38 AM, Robert Klemme <shortcutter@googlemail.com> 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:
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])
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...
Kind regards
robert
···
On 03.03.2008 11:20, Thomas Wieczorek wrote:
On Mon, Mar 3, 2008 at 10:38 AM, Robert Klemme > <shortcutter@googlemail.com> wrote:
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: