I'm trying to write a single line if else statement in a view.
<%= collection.name ? collection.name : @miniature.name %>
I want it to put collection.name if one exists, otherwise I want it to put @miniature.name
In Ruby, the condition and the then part of an if expression must be separated by either an expression separator (i.e. ; or a newline) or the then keyword. There is also a conditional operator in Ruby, but that is completely unnecessary.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
then is a delimiter to help Ruby identify the condition and the true-part of the expression. if condition then true-part else false-part end. then is optional unless you want to write an if expression in one line.
To make it even clearer, you can use logical OR
and ActiveSupport's
Object#presence
(to put collection.name
only if it exists and isn't blank):
<%= collection.name.presence || @miniature.name %>
If you want to display collection.name
if it's not nil
, but it's blank (empty string or string containing only whitespace), it will be enough to have:
<%= collection.name || @miniature.name %>
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