Is there is simpler way to write this ruby code:
if @canonical_url
@canonical_url
else
request.original_url
end
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.
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.
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.
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.
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
cond ? then_branch : else_branch
in your case.
@cononical_url ? @cononical_url : request.original_url
It is called a ternary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With