Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator within Rails view

I'm new to Rails, so forgive me if it's something simple, but it does seem as if though what I've written is correct. I'm using a ternary operator in my view to decide whether to add a class of active or not:

<li class="<% is_current_page('') ? 'active' : '' %>">

And I've debugged and know for sure that is_current_page('') is returning true.

like image 224
ediblecode Avatar asked Nov 15 '13 11:11

ediblecode


People also ask

How do I use ternary operator in Ruby on Rails?

The conditional ternary operator assigns a value to a variable based on some condition. This operator is used in place of the if-else statement. The operator first evaluates for a true or false value and then, depending upon the result of the evaluation, executes one of the two given statements​.

Does Ruby support ternary operator?

The ternary operator is a common Ruby idiom that makes a quick if/else statement easy and keeps it all on one line.

What is '?' In Ruby?

Functions that end with ? in Ruby are functions that only return a boolean, that is, true, or false. When you write a function that can only return true or false, you should end the function name with a question mark.

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.


2 Answers

You missed =

<li class="<%= is_current_page('') ? 'active' : '' %>">
like image 122
Amit Thawait Avatar answered Sep 23 '22 15:09

Amit Thawait


You probably wanted to do

<li class="<%= is_current_page('') ? 'active' : '' %>">
like image 33
bbozo Avatar answered Sep 22 '22 15:09

bbozo