2016-11-14 104 views
2

我今天在玩,意外地写了这个,现在我很高兴。发生病情时会发生什么情况?

i = 101 
case i 
    when 1..100 
    puts " will never happen " 
    when i == 101 
    puts " this will not appear " 
    else 
    puts " this will appear" 
end 

ruby​​的内部处理方式when i == 101就像i == (i == 101)

回答

5

结构

case a 
    when x 
    code_x 
    when y 
    code_y 
    else 
    code_z 
end 

相同的计算结果为

if x === a 
    code_x 
elsif y === a 
    code_y 
else 
    code_z 
end 

每个when调用的when参数的方法===,传球case参数作为参数(x === a是相同的x.===(a)) 。 ===方法与==稍有不同:它通常被称为“个案包容”。对于数字和字符串等简单类型,它与==是一样的。对于RangeArray对象,它是.include?的同义词。对于Regexp对象,它与match非常相似。对于Module对象,它会测试参数是否为该模块的实例或其后代的一个实例(基本上,如果x === a,则为a.instance_of?(x))。因此,在你的代码,

if (1..101) === i 
    ... 
elsif (i == 101) === i 
    ... 
else 
    ... 
end 

执行几乎同样的测试,

if (1..101).include?(i) 
    ... 
elsif (i == 101) == i 
    ... 
else 
    ... 
end 

注意,这里的case另一种形式的不使用===

case 
    when x 
    code_x 
    when y 
    code_y 
    else 
    code_z 
end 

这等同于

if x 
    code_x 
elsif y 
    code_y 
else 
    code_z 
end 
+1

读者:如果你看到这个答案和我的一些相似之处,你应该知道我的原始答案是不正确的混乱,这并没有被这个戴头盔的Rubiest所忽略。在我完成编辑的同时,他提交了他的答案。 –

0

如果你when i == 101其等同于:

i == (i == 101) 

which for your code is equal to 

101 == true # false 

if you do the when case as follows: 

when i == 101 ? i : false 

它会进入到该块段

i = 101 
case i 
    when 1..100 
    puts " will never happen " 
    when i == 101 ? i : false 
    puts " THIS WILL APPEAR " 
    else 
    puts " this will now NOT appear" 
end 
#> THIS WILL APPEAR 
+1

你应该使用一个proc代替,即'when - >(j){j == 101}' – Stefan

7

您的代码就相当于:

if (1..100) === 101 
    puts " will never happen " 
elsif (101 == 101) === 101 
    puts " this will not appear " 
else 
    puts " this will appear" 
end 

如果我们看一下我们看到Range#===

(1..100) === 101 

等同于:

(1..100).include?(101) 
    #=> false 

(101 == 101) === 101简化为:

true === 101 

我们从文档查看TrueClass#===这相当于:

true == 101 
    #=> false 

因此, else子句被执行。

相关问题