I have to put something in my .erb template , which uses conditional operator.

In the code below you can see I am checking the conditional value and printing the same value if its not nil.

<%= (@variable.value.nil?) ? "-" : @variable.value %>

I guess there should be a more shorter way to do this. As it really looks ugly to write same things twice.

3 Answers

Rajan Verma On Best Solutions

You can simply use the || operator like below.

<%= @variable.value || "-" %>
R Vom On

Try (OR) operator.

<%= @variable.value || "-" %> 


<%= @variable.value || #{any_variable_you_want_to_display_that_surely_contains_value}  %> 
spickermann On

When you are using Ruby on Rails then you can use the presence helper method which returns self only when self is present:

<%= @variable.value.presence || "-" %>

Compared to your version presence also handles cases in which @variable.value returns an empty string.