How is the conditional operator (? :) used in Ruby?
For example, is this correct?
<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It is the ternary operator, and it works like in C (the parenthesis are not required). It’s an expression that works like:
However, in Ruby,
ifis also an expression so:if a then b else c end===a ? b : c, except for precedence issues. Both are expressions.Examples:
Note that in the first case parenthesis are required (otherwise Ruby is confused because it thinks it is
puts if 1with 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: