Ruby 相当于 C# ?操作员
Possible Duplicate:
C# ?? operator in Ruby?
Is there a Ruby operator that does the same thing as C#'s ?? operator?
The ?? operator returns the left-hand
operand if it is not null, or else it
returns the right operand.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该运算符的名称是空合并运算符。我链接的原始博客文章涵盖了语言之间空合并的差异,已被删除。 C# 和 Ruby 空合并之间的较新比较可以在 此处。
简而言之,您可以使用
||
,如下所示:The name of the operator is the null-coalescing operator. The original blog post I linked to that covered the differences in null coalescing between languages has been taken down. A newer comparison between C# and Ruby null coalescing can be found here.
In short, you can use
||
, as in:如果您不介意合并 false,则可以使用 ||运算符:
如果 false 可以是有效值,则可以执行以下操作:
其中检查 b 是否为 nil,如果是,则将 c 的值赋给 a,如果不是,则将 b 赋给 a。
If you don't mind coalescing false, you can use the || operator:
If false can be a valid value, you can do:
Where b is checked for nil, and if it is, a is assigned the value of c, and if not, b.
请注意,Ruby 具有将通常的 null 合并到
[]
或0
或0.0
的特定功能。而不是
...您可以(因为
NilClass
实现了它们)只是做...这使得某些常见的设计模式,例如:
...看起来更好一点:
Be aware that Ruby has specific features for the usual null coalescing to
[]
or0
or0.0
.Instead of
...you can (because
NilClass
implements them) just do...This makes certain common design patterns like:
...look a bit nicer: