Ruby 案例中的条件会发生什么情况?
我今天玩的时候不小心写了这个,现在我很兴奋Ruby 案例中的条件会发生什么情况?,ruby,Ruby,我今天玩的时候不小心写了这个,现在我很兴奋 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 当i==101时,ruby如何在内部处理,类似于i==(i==101)?如果在i==101时执行,它相当于: i == (i == 101) wh
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
当i==101时,ruby如何在内部处理
,类似于i==(i==101)
?如果在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
if (1..100) === 101
puts " will never happen "
elsif (101 == 101) === 101
puts " this will not appear "
else
puts " this will appear"
end
(1..100).include?(101)
#=> false
true == 101
#=> 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
您的代码相当于:
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
if (1..100) === 101
puts " will never happen "
elsif (101 == 101) === 101
puts " this will not appear "
else
puts " this will appear"
end
(1..100).include?(101)
#=> false
true == 101
#=> false
如果我们看一看,我们就会看到这一点
(1..100) === 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
if (1..100) === 101
puts " will never happen "
elsif (101 == 101) === 101
puts " this will not appear "
else
puts " this will appear"
end
(1..100).include?(101)
#=> false
true == 101
#=> false
(101==101)==101
减少为:
true === 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
if (1..100) === 101
puts " will never happen "
elsif (101 == 101) === 101
puts " this will not appear "
else
puts " this will appear"
end
(1..100).include?(101)
#=> false
true == 101
#=> false
因此,执行else子句。结构
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)
)。==
方法与==
略有不同:它通常被称为“案例包容”。对于数字和字符串等简单类型,它与==
相同。对于范围
和数组
对象,它是的同义词。包含?
。对于Regexp
对象,它与match
非常相似。对于Module
对象,它测试参数是该模块的一个实例还是它的一个后代(基本上,如果x==a
则a.instance\u of?(x)
)。因此,在您的代码中
if (1..101) === i
...
elsif (i == 101) === i
...
else
...
end
它执行的测试与
if (1..101).include?(i)
...
elsif (i == 101) == i
...
else
...
end
请注意,还有另一种形式的案例
不采用=
:
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
读者:如果你看到这个答案和我的答案有一些相似之处,你应该知道我最初的答案是一个不正确的烂摊子,这个戴着石灰头盔的红宝石并没有忽视这一点。他在我完成编辑的同时提交了他的答案。你应该使用一个proc,即when->(j){j==101}