如何从 ruby​​ 中的字符串名称创建类实例? [英] How do I create a class instance from a string name in ruby?

查看:39
本文介绍了如何从 ruby​​ 中的字符串名称创建类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类的名称,我想创建该类的一个实例,以便我可以遍历该类架构中存在的每个 rails 属性.

I have the name of a class and I want to create an instance of that class so that I can loop through each rails attribute that is present in the schema of that class.

我该怎么做?

  1. 我将名称作为要检查的类的字符串
  2. 我想我需要实例化一个类实例,以便我可以
  3. 遍历它的属性并打印它们.

推荐答案

在 Rails 中,你可以这样做:

In rails you can just do:

clazz = 'ExampleClass'.constantize

纯红宝石:

clazz = Object.const_get('ExampleClass')

带模块:

module Foo
  class Bar
  end
end

你会使用

> clazz = 'Foo::Bar'.split('::').inject(Object) {|o,c| o.const_get c}
  => Foo::Bar 
> clazz.new
  => #<Foo::Bar:0x0000010110a4f8> 

这篇关于如何从 ruby​​ 中的字符串名称创建类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆