pil*_*row 6 ruby predicate ternary-operator conditional-operator
我喜欢明智地使用三元条件运算符.在我看来,它非常简洁.
但是,在ruby中,我发现我经常测试谓词方法,它们已经有了自己的问号:
some_method( x.predicate? ? foo : bar )
Run Code Online (Sandbox Code Playgroud)
这两个问号彼此如此接近,我感到震惊.是否存在等效的紧凑且可读的替代方案?
Jör*_*tag 12
在C中需要条件运算符的原因是因为条件语句是一个语句,即它不会(也不能)返回一个值.所以,如果你想从条件代码中返回一个值,那你就不走运了.这就是必须添加条件运算符的原因:它是一个表达式,即它返回一个值.
然而,在Ruby中,条件运算符完全是多余的,因为无论如何Ruby都没有语句.一切都是表达.具体来说,ifRuby中没有语句,只有一个if表达式.
而且既然if是表达式,你可以使用它而不是神秘的条件运算符:
some_method( if x.predicate? then foo else bar end )
Run Code Online (Sandbox Code Playgroud)
你唯一需要记住的是谓词需要用换行符,分号或者分号来终止then.所以,你做这个的前三次,你会转
if cond
foo
else
bar
end
Run Code Online (Sandbox Code Playgroud)
成
if cond foo else bar end
Run Code Online (Sandbox Code Playgroud)
并想知道为什么它不起作用.但在那之后,then(或分号)将自然而然地出现:
if cond; foo else bar end
if cond then foo else bar end
Run Code Online (Sandbox Code Playgroud)
你可以得到的最接近的简洁表达是
x.predicate? && foo || bar
Run Code Online (Sandbox Code Playgroud)
它有点像三元运算符,但更加神秘和丑陋.
这只是由query?方法上的糖引起的语法糖尿病的情况.我想我们只需要学会忍受它.
| 归档时间: |
|
| 查看次数: |
1584 次 |
| 最近记录: |