ruby - 在变量 Ruby 中使用类名创建的类实例

标签 ruby

我需要做这样的事情

class Foo
 define perform()
  puts 'hello'
 end
end

classname = 'Foo'

instance = create_instance(classname)
instance.perform();

这样的事情可能吗?如果是怎么办?

非常感谢!

最佳答案

你可以使用 const_get :

instance = Object.const_get(classname).new
instance.perform

关于ruby - 在变量 Ruby 中使用类名创建的类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10568173/

相关文章:

ruby - 如何在 Rhodes 中将字符串(ruby 哈希)解析为 JSON 或数组?

ruby-on-rails - Rails 4 elasticsearch使用多个搜索条件,结合了搜索功能

ruby - 数组中第一个非零值的索引

ruby-on-rails - end_of_week 返回不同日期

ruby - Rails3/ruby gem 中是否有将状态代码映射到消息的方法?

ruby-on-rails - Ruby on Rails 多个按钮

ruby - will_paginate 助手在 sinatra 和 mongoid 中未定义

ruby - PG Ruby Gem 在设置 PostgreSQL 连接时是否使用 pgpass?

mysql - 使用 id 从表中检索值

ruby - `File.exist?` 找不到存在的文件