ruby – ‘case’语句如何与常量一起使用?
发布时间:2020-12-17 03:36:23 所属栏目:百科 来源:网络整理
导读:我使用的是 Ruby 1.9.2和 Ruby on Rails 3.2.2.我有以下方法: # Note: The 'class_name' parameter is a constant; that is,it is a model class name.def my_method(class_name) case class_name when Article then make_a_thing when Comment then make_a
我使用的是
Ruby 1.9.2和
Ruby on Rails 3.2.2.我有以下方法:
# Note: The 'class_name' parameter is a constant; that is,it is a model class name. def my_method(class_name) case class_name when Article then make_a_thing when Comment then make_another_thing when ... then ... else raise("Wrong #{class_name}!") end end 我想理解为什么,在上面的case语句中,当我执行my_method(Article),my_method(Comment)等方法调用时,它总是运行else“part”. 我该如何解决这个问题?有人有建议如何处理这个? 解决方法
这是因为大小写调用===和
=== on Class(或者具体是Module,Class来自哪个类)实现如下:
这意味着除了Class&之外的任何常数.模块(例如Foo),Foo === Foo总是返回false.因此,您总是在case语句中获得else条件. 相反,只需调用对象本身而不是其类,或使用if语句. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |