如何在ruby中传递类名作为变量 [英] How to pass class name as variable in ruby
本文介绍了如何在ruby中传递类名作为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有另一个文件创建的foo.rb和main.rb文件。
I have foo.rb and main.rb files which was created by another file.
foo.rb:
class Foo
def initialize
@val = 1
end
end
main.rb:
file_name = gets.chomp()
require_relative(file_name)
class_name = file_name.capitalize
a = class_name.new()
p "This is val: #{a.val}"
但我得到一个错误:未定义的方法
Foo.rb:String(NoMethodError)`
But I get an error: undefined method
new' for "Foo.rb":String (NoMethodError)`
我的问题:如何传递类名作为值。
My question: How can I pass class name as a value.
推荐答案
您需要删除扩展...
You need to remove the extension...
class_name = Object.const_get(file_name.capitalize[/^[^.]*/])
这篇关于如何在ruby中传递类名作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文