0

Easy one for you: What's the Ruby equivalent of this in PHP?

return $x == 0 ? 1 : $x;

2 Answers 2

2

If you know that $x is a Numeric, then:

$x.zero? ? 1 : $x
Sign up to request clarification or add additional context in comments.

Comments

0

It's the same

 x == 0 ? 1 : x

The ||= shortcut is not applicable here, because 0 is not a "falsy" value, it's true.

3 Comments

Doh! Thanks! I thought I tried that but obviously not! Yes I was expecting ||= to work as PHP would too.
However, in Ruby, if is an expression, not a statement (in fact, everything is an expression in Ruby, there are no statements), so the use of the conditional operator is never necessary, and using if is often more readable: if x == 0 then 1 else x end.
@JörgWMittag: It depends. In this situation I find ternary operator much more readable. It's a matter of taste and background, I guess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.