Page 15 of The Ruby Way (2nd edition) presents a basic Ruby idiom for checking whether a string is empty or not.
I believe there are three ways to do it (if you can think of any others, leave a comment!). Two reasonably obvious, but one that’s quite idiomatic (the one that The Ruby Way mentions):
str.empty?– With this we simply ask a String object if it’s “empty.”
str.length > 0– With this we check whether the string has a length of more than zero – i.e. it’s not empty.
str– With this we check the first character of the string. If no first character is present, both Ruby 1.8 and 1.9 return
nil! This is particularly idiomatic and not something I’d considered before.
Of course, the shortest or most idiomatic route is not usually the best way to go when programming, but if you’re playing code golf, doing some obfuscation, or otherwise want to access the first character of the string anyway, option #3 is undeniably sneaky.
Note: Remember that while a string can only be empty or non-empty, a variable that you think is referring to a String object may well be nil! So often you need to check for nil as well as string length. You can do this with a simple