How do I use the conditional operator (? :) in Ruby?
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
puts true ? "true" : "false"
=> "true"
puts false ? "true" : "false"
=> "false"
Your use of ERB suggests that you are in Rails. If so, then consider truncate
, a built-in helper which will do the job for you:
<% question = truncate(question, :length=>30) %>