首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Ruby类类型和case语句

Ruby类类型和case语句
EN

Stack Overflow用户
提问于 2010-10-12 01:07:38
回答 2查看 49.1K关注 0票数 151

它们之间的区别是什么

case item.class
when MyClass
  # do something here
when Array
  # do something different here
when String
  # do a third thing
end

case item.class
when MyClass.class
  # do something here
when Array.class
  # do something different here
when String.class
  # do a third thing
end

出于某些原因,第一个有时有效,第二个不起作用,其他时候,第二个有效,第一个不起作用。为什么?哪种方式才是“正确”的呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-10-12 01:11:37

您必须使用:

case item
when MyClass
...

我也遇到了同样的问题:How to catch Errno::ECONNRESET class in "case when"?

票数 255
EN

Stack Overflow用户

发布于 2010-10-12 01:37:30

是的,Nakilon是正确的,你必须知道the ===操作符是如何在when子句中给出的对象上工作的。在Ruby中

case item
when MyClass
...
when Array
...
when String
...

是真的

if MyClass === item
...
elsif Array === item
...
elsif String === item
...

理解case是在调用一个threequal方法(例如MyClass.===(item)),该方法可以被定义为执行任何您想做的事情,然后您可以使用带有precisionw的case语句

票数 69
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3908380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档