How do I use the conditional operator (? :) in Ruby?

Mithun Sreedharan picture Mithun Sreedharan · Nov 23, 2010 · Viewed 342.2k times · Source

How is the conditional operator (? :) used in Ruby?

For example, is this correct?

<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>

Answer

user166390 picture user166390 · Nov 23, 2010

It is the ternary operator, and it works like in C (the parenthesis are not required). It's an expression that works like:

if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this

However, in Ruby, if is also an expression so: if a then b else c end === a ? b : c, except for precedence issues. Both are expressions.

Examples:

puts (if 1 then 2 else 3 end) # => 2

puts 1 ? 2 : 3                # => 2

x = if 1 then 2 else 3 end
puts x                        # => 2

Note that in the first case parenthesis are required (otherwise Ruby is confused because it thinks it is puts if 1 with some extra junk after it), but they are not required in the last case as said issue does not arise.

You can use the "long-if" form for readability on multiple lines:

question = if question.size > 20 then
  question.slice(0, 20) + "..."
else 
  question
end