ruby – 为什么switch语句与if语句的执行方式不同?
发布时间:2020-12-17 01:54:40 所属栏目:百科 来源:网络整理
导读:为什么if语句在下面的示例中起作用,而 switch statement则不起作用. 工作: if ''.class == String puts "yep,that's a string"end 不工作: case ''.classwhen String puts "yep,that's a string,but this case is never triggered"end 在上面的简单例子中,
为什么if语句在下面的示例中起作用,而
switch statement则不起作用.
>工作: if ''.class == String puts "yep,that's a string" end >不工作: case ''.class when String puts "yep,that's a string,but this case is never triggered" end 在上面的简单例子中,switch语句是矫枉过正的,但显然有一种情况是switch语句比DRyer更干扰elsifs 解决方法
这是因为case语句不使用==运算符,它使用===运算符(有时称为大小写相等运算符).这取决于运算符左侧的内容.所以,如果你要像这样转换case语句:
case "Some string" when String puts "It's a string!" else puts "It's not a string!" end 进入if语句,它将成为: if String === "Some string" puts "It's a string!" else puts "It's not a string!" end 请注意,Ruby会根据您的预期向后执行此操作,它会执行String ===“Some string”.这是因为你真正想做的是在这里调用Class#===,而不是String#===. ===运算符对任何对象的作用都取决于类.在Class#===的情况下,它大致相当于调用“Some string”.is_a?(String).但是如果你要做“a”===“b”,那么String#===方法大致相当于String#==. 它可能会让人感到困惑,但操作符的使用很大程度上是惯用的.换句话说,“when语句中的类对象”惯用语意味着测试case对象是否属于该类.我写了一篇关于这个的文章,它解释了一下,你可以读它here. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |