开发者

Why does this ruby case statement give an unexpected result?

开发者 https://www.devze.com 2023-02-16 03:00 出处:网络
Why does the following ruby code return \"\"instead of \"Code is empty\"? code = \"\" case code when code.empty?

Why does the following ruby code return "" instead of "Code is empty"?

code = ""
case code
when code.empty?
  "Code is empty"
el开发者_如何学Pythonse
  code
end


Because your code is comparing code to code.empty?, i.e., the result of code == code.empty?, which is false. A string can degrade to a boolean, but the explicit equality of '' == true will evaluate to false.


The expression code.empty? is a method call that calls the method empty? which returns the value true. The true value is then compared to the code variable using the expression true === code, which is false, so it executes the else block of code.

This is probably what you want instead:

case code
when ""
  "Code is empty"
else
  code
end

A simpler way to do it is by using the ternary operator:

code.empty? ? "Code is empty" : code
0

精彩评论

暂无评论...
验证码 换一张
取 消