Shu*_*huo 21 c# ruby null-coalescing-operator
可能重复:
C#?? Ruby中的运算符?
是否有一个Ruby操作符与C#一样做?运营商?
该?? 如果左侧操作数不为null,则运算符返回左侧操作数,否则返回右侧操作数.
Chr*_*man 31
运算符的名称是null-coalescing运算符.我链接到的原始博客文章涵盖了语言之间空合并的差异已被删除.可以在此处找到C#和Ruby null合并之间的较新比较.
简而言之,您可以使用||,如:
a_or_b = (a || b)
Run Code Online (Sandbox Code Playgroud)
Sea*_*ill 16
如果你不介意合并假,你可以使用|| 运营商:
a = b || c
Run Code Online (Sandbox Code Playgroud)
如果false可以是有效值,则可以执行以下操作:
a = b.nil? ? c : b
Run Code Online (Sandbox Code Playgroud)
其中b被检查为nil,如果是,则a被赋值为c,如果不是,则b.
请注意,Ruby具有通常将null合并为[]or 0或or的特定功能0.0。
代替
x = y || [] # or...
x = y || 0
Run Code Online (Sandbox Code Playgroud)
...您可以(因为NilClass实现了它们)只是做...
x = y.to_a # => [] or ..
x = y.to_i # or .to_f, => 0
Run Code Online (Sandbox Code Playgroud)
这使得某些常见的设计模式如下:
(x || []).each do |y|
Run Code Online (Sandbox Code Playgroud)
...看起来更好一些:
x.to_a.each do |y|
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8487 次 |
| 最近记录: |