加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 当你有一个没有参数的case语句而when子句是lambdas时会

发布时间:2020-12-17 04:00:52 所属栏目:百科 来源:网络整理
导读:此代码无法按预期执行: case when - { false } then "why?" else "This is what I expect" end # = "why?" 这也不是 casewhen -(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子句在两种情况下都执行,这必然意味着没有调用我提供给when子句的lambda.我理解,无论when子句的主题是什么,都应该调用case相等运算符===.我想知道在没有提供参数的情况下,===的另一边发生了什么.我以为它可能是零,但它不能是:

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

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

这按预期执行,如果正在执行,将导致我预期的案例结果或异常.有人可以解释上面的结果吗?似乎没有使用case等于运算符,但是第一个when子句的计算结果为true.顺便说一句,我这样做是因为一个案例的输出可以用于变量赋值,而且它有少量冗长,然后有几个elsif子句.我希望能够在没有参数的case语句中使用任意Proc.

解决方法

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

正如The Pickaxe(http://pragprog.com/book/ruby3/programming-ruby-1-9)所说,有两种形式的案例陈述.

The first allows a series of conditions to be evaluated,executing
code corresponding to the first condition that is true: case when ?
boolean-expression ?+ ? then ? …

The second form of a case expression takes a target expression
following the case keyword. case target when ? comparison ?+ ? then ?

在您的情况下(没有目标的情况)任何非false或nil的表达式(例如Proc或字符串’cat’)的计算结果为true.除非你打电话,否则Proc不会被执行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读