我在Ruby中有一段代码如下:
def check
if a == b || c == b
# execute some code
# b = the same variable
end
end
Run Code Online (Sandbox Code Playgroud)
这可以写得像
def check
if a || c == b
# this doesn't do the trick
end
if (a || c) == b
# this also doesn't do the magic as I thought it would
end
end
Run Code Online (Sandbox Code Playgroud)
或者以我不需要输入b两次的方式.这是出于懒惰,我想知道.
und*_*gor 20
if [a, c].include? b
# code
end
Run Code Online (Sandbox Code Playgroud)
然而这是比代码显著慢要避免-至少只要a,b并且c是基本的数据.我的测量结果显示因子为3.这可能是由于Array创建了额外的对象.所以你可能不得不在这里权衡DRY和性能.但通常情况下,这并不重要,因为这两种变体都不需要很长时间.
虽然不完全相同a == b || a == c,但case语句提供了以下语法:
case a
when b, c then puts "It's b or c."
else puts "It's something else."
end
Run Code Online (Sandbox Code Playgroud)
随意打开最近的Ruby教科书,阅读有关case语句如何工作的内容.Spoiler:它通过调用#===比较对象的方法来工作:
a = 42
b, c = Object.new, Object.new
def b.=== other; puts "b#=== called" end
def c.=== other; puts "c#=== called" end
Run Code Online (Sandbox Code Playgroud)
现在跑
case a
when b, c then true
else false end
Run Code Online (Sandbox Code Playgroud)
这为您提供了很大的灵活性.它需要在后台工作,但在你做完后,在前台看起来像魔术.
| 归档时间: |
|
| 查看次数: |
3078 次 |
| 最近记录: |