Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is good if an empty string is truthy? [closed]

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?

like image 934
sawa Avatar asked Apr 13 '13 15:04

sawa


2 Answers

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.

like image 102
sawa Avatar answered Nov 15 '22 05:11

sawa


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.

like image 41
deceze Avatar answered Nov 15 '22 06:11

deceze