C# ?? Ruby 中的运算符?
是否可以实施? Ruby 中的运算符?
a = nil
b = 1
x = a ?? b # x should == 1
x = b ?? 2 # x should == 1
Is it possible to implement the ?? operator in Ruby?
a = nil
b = 1
x = a ?? b # x should == 1
x = b ?? 2 # x should == 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 Ruby 中,短路布尔运算符(
||
、&&
、and
和or
)不返回 true 或 false,而是返回确定整个表达式结果的第一个操作数。 这是可行的,因为 Ruby 对真理有一个相当简单的想法。 或者更确切地说,它有一个相当简单的错误概念:nil
是假的,显然false
是假的。 其他一切都是正确的。因此,由于当至少一个其操作数为真时
||
为真,并且操作数是从左到右计算的,这意味着a || 当
返回a
为 true 时,ba
。 但当a
为假时,则表达式的结果仅依赖于b
,因此返回b
。这意味着,由于
nil
为 false,因此您可以在给出的示例中使用||
而不是??
。 (还有一个漂亮的a ||= b
运算符,其工作方式类似于a || a = b
,但不完全一样。)但是, only 有效,因为您在示例中没有使用布尔值。 如果您希望处理布尔值,那么这是行不通的:
在这种情况下,您必须使用
#nil?
和条件表达式:或使用三元条件运算符:
如果您想要到,你可以用一个很好的方法来包装它:
这个可爱的片段是由多态性、开放类以及
nil
实际上是一个代表虚无的对象(与,比如说 Java,其中null
实际上什么都没有。)In Ruby, the short-circuiting Boolean operators (
||
,&&
,and
andor
) do not returntrue
orfalse
, but rather the first operand that determines the outcome of the entire expression. This works, because Ruby has a rather simple idea of truth. Or rather, it has a rather simple idea of falsehood:nil
is false, and obviouslyfalse
is false. Everything else is true.So, since
||
is true when at least one of its operands is true, and operands are evaluated from left to right, this means thata || b
returnsa
, whena
is true. But whena
is false, then the outcome of the expression is solely dependent onb
, and thusb
is returned.That means that, because
nil
is false, you can just use||
instead of??
for the examples that you gave. (There is also the niftya ||= b
operator, which kind of works likea || a = b
, but not quite.)However, that only works, because you don't use Booleans in your examples. If you expect to deal with Boolean values, that won't work:
In that case, you will have to use
#nil?
, and a conditional expression:or using the ternary conditional operator:
If you want to, you can wrap that up in a nice method:
This cute snippet brought to you by polymorphism, open classes and the fact that
nil
is actually an object representing nothingness (unlike, say, Java, wherenull
is actually nothing).您正在寻找条件赋值:
和 || 操作员
You're looking for conditional assignment:
and the || operator
它(C# 中的
??
)称为合并运算符。It (
??
in C#) is called the coalesce operator.有 coalesce gem,它是您所能得到的最接近的。
There is the coalesce gem, which is as close as you'll get.
Ruby 有一个空合并运算符
&.
,称为“安全导航运算符”:这并不完全是您所要求的,但这个问题在 google 上的“ruby null合并运算符”排名如此之高值得一提的是。
Ruby has a null coalescing operator
&.
, called the "Safe Navigation Operator":It's not exactly what you're asking for, but this question ranks so high on google for "ruby null coalescing operator" that it's worth mentioning here.