Reputation: 108
In Ruby, We often use ternary operator for checking conditions. Similarly we have or operator(||) for using either of the two.
I have scenario where I can use in both ways: Ternary Operator
@question = question.present? ? question : Question.new
Or Operator
@question = question || Question.new
What is the difference between these conditions as both gives the same output? Also which one is better to use in controller method as I am not experienced to decide by my own.
Upvotes: 3
Views: 1739
Reputation: 593
The ternary operator checks the condition and if it is true returns the first value, else returns the second value. Using it you can specify the condition, upon which to decide what value to return.
The OR operator works the following way - if the first expression is not nil
or false
, return it, otherwise return the second expression. Here you are not able to specify the condition, because the check is made directly on the first value you want to return. The OR operator can be represented like:
if question
@question = question
else
@question = Question.new
end
Deciding which one to use depends entirely on the condition you want to apply. In your case you want to assure that the question
is not nil
. So the OR operator is fine in this case and is shorter than the ternary operator.
Hope that gives some clarification.
Upvotes: 1
Reputation: 51191
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.
Upvotes: 8
Reputation: 16506
For this case you can use any one of them, both are same.
I would prefer using @question = question || Question.new
as its easier to read.
However there are many cases where both ||
and ternary operators have different outputs. So you cannot take this for granted.
Upvotes: 0