Given the rails following code:
if params["is_happy"].blank? happiness = "unknown" else happiness = params["is_happy"] ? "happy" : "sad" end
Quick what is the value of happiness in the following code if :
params["is_happy"] == true
If you said, “Dah! ‘happy’ of course Mr. Obvious”, you are right. Good job!
params["is_happy"] == nil
Well of course, ‘unknown’.
last one, how about this one:
params["is_happy"] == false
If you said, if you said ‘sad’ you have the same mental bug as mine but if you said ‘unknown’, you know better because that is the correct answer.
For the longest time, I thought blank was empty/nil check actually it is more of ‘truthiness’ check if you consider empty string, array and hash as ‘falsy’.
I am not the only one, I did a quick check with a co-worker and he was also not sure and upon searching, I found this aptly named issue:
They updated the documentation based on this issue but the implementation has not changed for 3 years since it was introduced. If I get a chance to go back in time I would make it as suggested in the above issue:
def blank? respond_to?(:empty?) ? !!empty? : self.nil? end
Doing that now will potentially break a lot of people and might not be a great idea.