How to Use the Conditional Operator (? :) in Ruby

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

Ruby ternary operator if else

@skill = @user.skill || Skill.new

If the value of @user.skill if nil, it will asign the next value( Skill.new) to @skill.

Is the ternary operator ?: defined as a method in Ruby?

Is the ternary operator in Ruby really just a syntactic sugar for if ... then ... else ... end statements?

Yes.

From doc/syntax/control_expressions.rdoc

You may also write a if-then-else expression using ? and :. This ternary if:

input_type = gets =~ /hello/i ? "greeting" : "other"

Is the same as this if expression:

input_type =
if gets =~ /hello/i
"greeting"
else
"other"
end

"According to this book, "every operation is a method call on some object and returns a value." In this sense, if the ternary operator represents an operation, it is a method call on an object with two arguments."

if, unless, while, and until are not operators, they are control structures. Their modifier versions appear in the operator precedence table because they need to have precedence in order to be parsed. They simply check if their condition is true or false. In Ruby this is simple, only false and nil are false. Everything else is true.

Operators are things like !, +, *, and []. They are unary or binary. You can see a list of them by calling .methods.sort on various objects. For example...

2.4.3 :004 > 1.methods.sort
=> [:!, :!=, :!~, :%, :&, :*, :**, :+, :+@, :-, :-@, :/, :<, :<<, :<=, :<=>, :==, :===, :=~, :>, :>=, :>>, :[], :^, :__id__, :__send__, etc...

Note that in Smalltalk, from which Ruby borrows heavily, everything really is a method call. Including the control structures.

How can I use the ternary operator with multiple values?

Since a ternary operator is exactly that (an operator), you can't split it over multiple instructions.

However, blocks make it possible to "squash" multiple instructions into a single expression.

def my_withdraw(pin_number,amount)
puts (
pin_number == @pin ?
begin
@balance -= amount
"Withdrew #{amount}."
end :
pin_error
)
end

Of course, this is completely illegible and I would never recommend you use that sort of syntax in the real world. But for the sake of science, why not.

How do you write inline Ruby on Rails ternary operators in an HTML tag with white space?

You can write it like this

<li class="<%= loc == @ruby_var ? "nav-item active" : "nav-item" %>">
# ...
</li>

Note the " outside of the erb expression.

Or you can use tag helper like this

<%= tag.li, class: ["nav-item", (:active if loc == @ruby_var)] do %>
# ...
<% end %>

I like the second option better because I prefer not to mix HTML and ERB when describing a tag.

ruby idiom: predicates and the conditional operator

The closest succinct expression you can get is

x.predicate? && foo || bar

which acts sort of a ternary operator, but more cryptic and ugly.

It's just a case of syntactic diabetes caused by the sugar on the query? methods. I guess we'll just have to learn to live with it.

How to use multiple assignment with a ternary operator?

Here is the correct syntax for multiple assignment using a ternary operator:

foo, bar = baz ? [1, 2] : [3, 4]

The return values for true and false must be wrapped in brackets.

I hope this helps :)

Ruby ternary operator (or) or operator

The difference here is that, for example, [].present? or ''.present? both return false. So:

question = ''
@question = question.present? ? question : Question.new
# => result of Question.new
@question = question || Question.new
# => ''

But it shouldn't mean anything in your case if question can only hold nil or Question instance (which is always present, assuming it's a regular ActiveRecord model). So it's more a matter of personal taste.



Related Topics



Leave a reply



Submit