How to pass class name as variable in ruby [duplic

2019-04-17 11:55发布

This question already has an answer here:

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}"

But I get an error: undefined methodnew' for "Foo.rb":String (NoMethodError)`

My question: How can I pass class name as a value.

1条回答
一纸荒年 Trace。
2楼-- · 2019-04-17 12:14

You need to remove the extension...

class_name = Object.const_get(file_name.capitalize[/^[^.]*/])
查看更多
登录 后发表回答