简体   繁体   English

什么是Ruby的C?:运算符?

[英]What's the Ruby equivalent of C ?: operator?

C has short conditional branch operator. C具有短条件分支运算符。

int a = 1 < 2 ? 3 : 4;

What's the equivalent in Ruby? Ruby中的等效功能是什么?

Ruby也有三元运算符,您可以用相同的方式进行操作。

a = 1 < 2 ? 3 : 4
a = true  ? 'a' : 'b' #=> "a"
b = false ? 'a' : 'b' #=> "b"

You can also use a whole if statement since it is also an expression: 您也可以使用整个if语句,因为它也是一个表达式:

a = if 1 < 2 then 3 else 4 end

or even: 甚至:

a = if 1 < 2
      3
    else
      4
    end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM