Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 当您有一个没有参数的case语句并且when子句是lambdas时会发生什么?_Ruby - Fatal编程技术网

Ruby 当您有一个没有参数的case语句并且when子句是lambdas时会发生什么?

Ruby 当您有一个没有参数的case语句并且when子句是lambdas时会发生什么?,ruby,Ruby,此代码的执行情况与我预期的不同: case when -> { false } then "why?" else "This is what I expect" end # => "why?" 这也不是 case when ->(x) {false} then "why?" else "This is what I expect" end # => "why?" 在这两种情况下都会执行第一个then子句,这必

此代码的执行情况与我预期的不同:

case    
when -> { false } then "why?"        
else "This is what I expect"        
end      
# => "why?"
这也不是

case
when ->(x) {false} then "why?"  
else "This is what I expect"
end  
# => "why?"
在这两种情况下都会执行第一个
then
子句,这必须意味着在未调用
子句时向
提供lambda I。我理解,当
子句是时,应该对
的任何主题调用大小写相等运算符
==
。我想知道当
案例
没有参数时,
==
的另一面会发生什么。我想可能是
nil
,但不可能是:

-> {false} === nil
# => ArgumentError: wrong number of arguments (1 for 0)

->(x) {false} === nil
# => false

这将按预期执行,如果执行,将导致预期的
案例
结果或异常。有人能解释一下上面的结果吗?似乎根本没有使用大小写相等运算符,但是第一个
when
子句的计算结果为
true
。顺便说一句,我这样做是因为
case
的输出可以用于变量赋值,并且它比有几个
elsif
子句要简单。我希望能够在没有参数的case语句中使用任意的
Proc
s。

您可以使用不带参数的
case
语句来执行类似于
if
语句的操作。例如:

case
when x > 0 then puts "positive"
else puts "negative"
end
您假设它试图与
nil
进行比较,但事实并非如此。相反,当没有参数时,
case
语句只测试“truthy”值(除了
nil
false
之外的任何值)。因此,当它第一次点击
when
语句时,它会检查
Proc
(意思是实际的ruby
Proc
对象,不是执行
Proc
的结果)是
nil
还是
false
,而不是。因为它是“真实的”,所以代码会被执行

尝试此操作,您将注意到
过程
甚至从未被调用/执行过(您将只看到
“bar”
,而不是
“foo”
):

产出:

why?
why?
This is what I expect
正如Pickaxe()所说,case语句有两种形式

第一种方法允许对一系列条件进行评估、执行 与第一个条件相对应的代码为true:case whenè 布尔表达式›+然后›

case表达式的第二种形式采用目标表达式 跟随case关键字。当è比较›+è然后›时的案例目标


在您的情况下(
case
无目标),任何非
false
nil
(如Proc或字符串“cat”)的表达式都计算为true。除非您
调用它,否则不会执行该过程。

case    
when -> { false } then puts "why?"        
else puts "This is what I expect"        
end

case    
when 'cat' then puts "why?"        
else puts "This is what I expect"        
end

case    
when -> { false }.call then puts "why?"        
else puts "This is what I expect"        
end
why?
why?
This is what I expect