Hopstream
Hopstream

Reputation: 6451

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

Upvotes: 10

Views: 15265

Answers (2)

Chuck
Chuck

Reputation: 237010

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

Upvotes: 21

Justin Wood
Justin Wood

Reputation: 10041

cond ? then_branch : else_branch

in your case.

@cononical_url ? @cononical_url : request.original_url

It is called a ternary.

Upvotes: 9

Related Questions