re: Be careful when memoizing booleans! VIEW POST


You're confusing the value of a with what the statement a = false if a.nil? is returning.

The console prints the output value of the whole statement; not necessarily the value of a.

If the value of a did change (as in, when it was assigned to), then that new value will print in the console. But if a doesn't change, then nil will be printed.

irb(main):001:0> a = false if a.nil?
=> false # this false is what "a = false if a.nil?" returned. It's false because 'a' was set to 'false'.
irb(main):002:0> a
=> false
irb(main):003:0> a = false if a.nil?
=> nil # this nil is what "a = false if a.nil?" returned. It's nil because 'a' was NOT set to anything.
irb(main):004:0> a
=> false

🤦 Of course. Thanks for the explanation. I'd convinced myself that it was returning the variable's value. Doh!

So, in my case I would use it like so:

  def happy?
    @happy = post_complete? if @happy.nil?
code of conduct - report abuse