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

后端 未结 4 1958
既然无缘
既然无缘 2020-11-29 18:55

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.

<
4条回答
  •  迷失自我
    2020-11-29 19:29

    Try this:

    Kernel.const_get("MyClass").new
    

    Then to loop through an object's instance variables:

    obj.instance_variables.each do |v|
      # do something
    end
    

提交回复
热议问题