eonil
eonil

Reputation: 86075

What's the Ruby equivalent of C ?: operator?

C has short conditional branch operator.

int a = 1 < 2 ? 3 : 4;

What's the equivalent in Ruby?

Upvotes: 0

Views: 76

Answers (3)

mu is too short
mu is too short

Reputation: 434745

You can also use a whole if statement since it is also an expression:

a = if 1 < 2 then 3 else 4 end

or even:

a = if 1 < 2
      3
    else
      4
    end

Upvotes: 2

Ramiz Raja
Ramiz Raja

Reputation: 6030

Ruby too have ternary operator, you can do it in the same way.

a = 1 < 2 ? 3 : 4

Upvotes: 4

wim
wim

Reputation: 363053

a = true  ? 'a' : 'b' #=> "a"
b = false ? 'a' : 'b' #=> "b"

Upvotes: 2

Related Questions