Ruby 相当于 C# ?操作员

发布于 2024-10-10 22:21:48 字数 467 浏览 0 评论 0原文

可能的重复:
C# ?? Ruby 中的运算符?

是否有一个 Ruby 运算符可以与 C# 的 ?? 运算符执行相同的操作?

?? 运算符返回左侧 操作数如果不为空,否则为 返回正确的操作数。

来自http://msdn.microsoft.com/en-us/library/ms173224。 ASPX

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.

from http://msdn.microsoft.com/en-us/library/ms173224.aspx

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤单情人 2024-10-17 22:21:48

该运算符的名称是空合并运算符。我链接的原始博客文章涵盖了语言之间空合并的差异,已被删除。 C# 和 Ruby 空合并之间的较新比较可以在 此处

简而言之,您可以使用 ||,如下所示:

a_or_b = (a || b)

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:

a_or_b = (a || b)
千と千尋 2024-10-17 22:21:48

如果您不介意合并 false,则可以使用 ||运算符:

a = b || c

如果 false 可以是有效值,则可以执行以下操作:

a = b.nil? ? c : b

其中检查 b 是否为 nil,如果是,则将 c 的值赋给 a,如果不是,则将 b 赋给 a。

If you don't mind coalescing false, you can use the || operator:

a = b || c

If false can be a valid value, you can do:

a = b.nil? ? c : b

Where b is checked for nil, and if it is, a is assigned the value of c, and if not, b.

橘和柠 2024-10-17 22:21:48

请注意,Ruby 具有将通常的 null 合并到 []00.0 的特定功能。

而不是

x = y || [] # or...
x = y || 0

...您可以(因为 NilClass 实现了它们)只是做...

x = y.to_a # => [] or ..
x = y.to_i # or .to_f, => 0

这使得某些常见的设计模式,例如:

(x || []).each do |y|

...看起来更好一点:

x.to_a.each do |y|

Be aware that Ruby has specific features for the usual null coalescing to [] or 0 or 0.0.

Instead of

x = y || [] # or...
x = y || 0

...you can (because NilClass implements them) just do...

x = y.to_a # => [] or ..
x = y.to_i # or .to_f, => 0

This makes certain common design patterns like:

(x || []).each do |y|

...look a bit nicer:

x.to_a.each do |y|
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文