gpt4 book ai didi

ruby - 如何检查一个类是否已经存在于 Ruby 中

转载 作者:数据小太阳 更新时间:2023-10-29 06:20:06 25 4
gpt4 key购买 nike

如何检查 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.     ....."

最佳答案

您可以使用 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;我怀疑这是否会用于任何严肃的应用程序,但值得了解安全风险。

关于ruby - 如何检查一个类是否已经存在于 Ruby 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1187089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com