In groovy, we have something like this:
condition ? 'value if true' : 'value if false'
It get even nicer if you considder this form:
condition ?: 'value if false'
where the true case will just return the condition as the value.
Consider:
book.author ?: 'unknown'
which will return author.toString() if it's not false/null or 'unknown'.
I've long thought Ruby lacked that elegance and so often resorted to the very cumbersome
book.author ? book.author : 'unknown'
until I stumbled onto this (even more elegant) approach:
book.author || 'unknown'
One can take this one step further, and chain them up. The first 'true' output is returned:
book.author || book.publisher || 'unknown'
or even
author.books && author.books.first || 'unpublished'
This latter form will prevent "null.first" errors.
book.author ?: 'unknown'
which will return author.toString() if it's not false/null or 'unknown'.
I've long thought Ruby lacked that elegance and so often resorted to the very cumbersome
book.author ? book.author : 'unknown'
until I stumbled onto this (even more elegant) approach:
book.author || 'unknown'
One can take this one step further, and chain them up. The first 'true' output is returned:
book.author || book.publisher || 'unknown'
or even
author.books && author.books.first || 'unpublished'
This latter form will prevent "null.first" errors.