如何检查类在Ruby中是否已经存在?
我的代码是:
puts "enter the name of the Class to see if it exists"
nameofclass=gets.chomp
eval (" #{nameofclass}...... Not sure what to write here")
我在考虑使用:
eval "#{nameofclass}ancestors. ....."
发布于 2009-07-27 09:33:55
您可以使用Module.const_get
来获取字符串引用的常量。它将返回常量(通常类由常量引用)。然后,您可以检查该常量是否为类。
我会按照这样的思路做一些事情:
def class_exists?(class_name)
klass = Module.const_get(class_name)
return klass.is_a?(Class)
rescue NameError
return false
end
此外,如果可能,我在接受用户输入时总是避免使用eval
;我怀疑这是否会用于任何严肃的应用程序,但值得注意其中的安全风险。
发布于 2009-07-27 08:52:05
也许你可以用defined来做呢?
例如:
if defined?(MyClassName) == 'constant' && MyClassName.class == Class
puts "its a class"
end
注意:类检查是必填项,例如:
Hello = 1
puts defined?(Hello) == 'constant' # returns true
要回答原来的问题:
puts "enter the name of the Class to see if it exists"
nameofclass=gets.chomp
eval("defined?(#{nameofclass}) == 'constant' and #{nameofclass}.class == Class")
发布于 2010-05-29 09:19:41
如果您通过调用Module.const_get
来查找某个范围内的常量,则可以避免从Module#const_defined?("SomeClass")
中抢救NameError。
调用它的常见作用域是Object,例如:Object.const_defined?("User")
。
参见:"Module“。
https://stackoverflow.com/questions/1187089
复制相似问题