Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails single line if else statement

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

like image 418
Ossie Avatar asked Mar 26 '14 15:03

Ossie


People also ask

How do you write if else in one line Ruby?

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.

What is the format of conditional operator?

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.

What is then in Ruby?

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.


1 Answers

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 %>
like image 75
Marek Lipka Avatar answered Sep 27 '22 17:09

Marek Lipka