Ruby ternary operator (or) or operator

Madhusudhan

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.

Marek Lipka

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related