4 ms·
Not GP, but I really like [] being false in ruby and python because I often want to ask "is this variable that should hold a collection holding a collection of
by SonOfLilit 5y ago
Not GP, but I really like [] being false in ruby and python because I often want to ask "is this variable that should hold a collection holding a collection of things, or is it empty/false?"
- PufPufPuf 5y agoI always found it strange that in Python, stuff doesn't get implicitly cast to string (even Java does that!), but for whatever reason the idiomatic way to check if a collection is empty is to do "if collection:", implicitly casting to bool.
- heavyset_go 5y agoNothing gets casted to a bool in Python if statements.
- djur 5y ago[] is truthy in Ruby. Only false and nil are falsy.
- emmelaich 5y agoYeah, sadly zero is not falsy in Ruby.
- dschooh 5y ago[] is truthy in Ruby but there is #empty? on collection types. Rails also has #blank? which additionally works on false and nil.
- hyperhopper 5y agoLuckily, most languages have a `.empty()` method! You should use that instead for readability purposes.
- derekbaker783 5y agoAnd in that vein, JS has some().
- alerighi 5y agoWhy an array with zero element should be false? It doesn't make a lot of sense. And writing if (array.length > 0) is more explicit than writing if (array) anyway. Even in python, I prefer to be explicit and say if len(array) > 0 than to rely on implicit conversion rules.
- marcosdumay 5y agoPersonally, I don't like if even accepting things that are not boolean. But an empty array being false makes exactly as much sense as an empty string being false, and both should have always the same behavior. If you want objects to behave like dictionaries, an empty object should also behave the same, by the way.
- heavyset_go 5y agoI'd argue that `if empty_list` is already explicit in Python.
- 65 5y agoIt would be better if Javascript had Array.empty() instead of comparing array length. It would make things even more explicit and more convenient.
- dorianmariefr 5y agoYou are thinking about `[].present?` I think