Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby short hand for simple if else condition

Is there is simpler way to write this ruby code:

if @canonical_url
    @canonical_url
else
    request.original_url
end
like image 855
Hopstream Avatar asked Dec 24 '13 19:12

Hopstream


People also ask

What is the use of if else statement in Ruby?

Ruby if-else statements are used for testing the condition. The execution of the if block code is only possible if the condition whether the else code block will be executed. If else statements are used for testing the condition.The execution of the if block code is only possible if the condition whether the else code block will be executed.

What happens if none of the conditions is true ruby?

If none of the conditions is true, then the final else statement will be executed. In Ruby ternary statement is also termed as the shortened if statement. It will first evaluate the expression for true or false value and then execute one of the statements.

What are the conditional statements available in Ruby?

Here, we will explain all the conditional statements and modifiers available in Ruby. if expressions are used for conditional execution. The values false and nil are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif.

What is the use of if-else in Ruby?

Similarly, in Ruby, the if-else statement is used to test the specified condition. If statement in Ruby is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.


2 Answers

This pattern is what the or-operator is for.

@canonical_url || request.original_url

Or, in cases where the first branch isn't just the result if the test, the conditional operator works as well:

some_condition ? @canonical_url : request.original_url
like image 81
Chuck Avatar answered Oct 22 '22 15:10

Chuck


cond ? then_branch : else_branch

in your case.

@cononical_url ? @cononical_url : request.original_url

It is called a ternary.

like image 24
Justin Wood Avatar answered Oct 22 '22 16:10

Justin Wood