How to pass class name as variable in ruby [duplic

2019-04-17 11:58发布

问题:

This question already has an answer here:

  • How do I create a class instance from a string name in ruby? 4 answers

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:

You need to remove the extension...

class_name = Object.const_get(file_name.capitalize[/^[^.]*/])