In Ruby, an empty string ""
is truthy with respect to conditionals. And I see many people struggling with this fact. Ruby on Rails's blank?
is one attempt to overcome this problem. On the other hand, it is not immediately obvious when such specification becomes convenient. Is there any use case where this fact becomes handy, or will there be a theoretical problem if it were otherwise?
I think I came up with the answer. Probably, it is for theoretical reason and for efficiency. Drawing a line between different instances of a single class is theoretically more complicated than drawing a line between classes, and would require more computation. If ""
were falesy, then the Ruby internal would have to check the string's length each time there is a string in a condition. Instead, if the truethyness can be judged just by the class, which happens to be the case, then it would be much more efficient. Perhaps this is also the reason why false
and true
are not subsumed under a single class Boolean
but belong to independent classes respectively.
Another possibility is that there are only one instances of false
and nil
, so dealing with that internally in Ruby would only require to check the pointer/object id, whereas strings are mutable, and would require more complexity to check for emptyness.
Reducing the number of things that are considered falsey is a good thing. It simplifies the language, simplifies the boolean rules, makes them easier to remember and apply and thereby reduces bugs.
Just look at the mess PHP is in: false
, 0
, 0.0
, '0'
, ''
, null
and array()
are all falsey, which keeps surprising many people every day.
If you want to test for an empty string, test for an empty string. You should know whether your variable contains a string or a boolean and be able to test accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With