Ruby 这个';案例';语句是否与常量一起工作?
我正在使用Ruby1.9.2和RubyonRails 3.2.2。我有以下方法:Ruby 这个';案例';语句是否与常量一起工作?,ruby,class,constants,switch-statement,Ruby,Class,Constants,Switch Statement,我正在使用Ruby1.9.2和RubyonRails 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 .
# 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
我想理解为什么在上面的案例中
语句中,当我执行方法调用时,它总是运行else
“part”,比如我的方法(文章)
,我的方法(注释)
等等
我怎样才能解决这个问题?是否有人建议如何处理此问题?将对象引用传递给该方法,因为在后台它使用===运算符,因此这些操作将失败。e、 g
obj = 'hello'
case obj.class
when String
print('It is a string')
when Fixnum
print('It is a number')
else
print('It is not a string')
end
另一方面,这样做很好:
obj = 'hello'
case obj # was case obj.class
when String
print('It is a string')
when Fixnum
print('It is a number')
else
print('It is not a string')
end
请参阅“如何在Ruby中编写switch语句”的相关答案,这是因为
case
调用==
,并且(或者具体地说,是哪个模块,哪个类从哪个模块派生)是这样实现的:
mod==obj
→ <代码>真或假
如果obj
是mod
的实例或mod
的后代之一,则大小写相等返回true
。对模块的使用有限,但可以在case语句中按类对对象进行分类
这意味着对于除类
和模块
(例如Foo
)以外的任何常量,Foo===Foo
始终返回false
。因此,您总是在案例
语句中得到else
条件
相反,只需使用对象本身而不是其类调用
case
,或者使用if
语句。如果只想比较名称的相等性,可以将添加到类常量中
def my_method(class_name)
case class_name.to_s
when 'Article'
make_a_thing
when 'Comment'
make_another_thing
... ...
end
end
是否因为case
语句使用了=
,而类不能被包含到自身中?如何调用此方法?也就是说,你向它传递了什么论据?这让一切都不同了。@Alex Wayne-我正在传递常量名(模型类名)。如问题中所述,我运行的方法有my_method(Article)
,my_method(Comment)
等等。@user12882您应该将class_name
变量重命名为klass
,以避免混淆。您所称的模型类名是一个名称,因此是一个字符串。您实际传递的是Class
。这实际上是错误的<代码>类===类
为真
Module===Module
也是true
@sawa。更新。这是正确的,因为类
和模块
实际上都是类
的实例,它是从模块
派生而来的。(这不是令人难以置信的吗?)