루비의 문자열 이름으로 클래스 인스턴스를 어떻게 생성합니까? 클래스의 스키마에있는 각

클래스의 이름이 있고 해당 클래스의 스키마에있는 각 레일 속성을 반복 할 수 있도록 해당 클래스의 인스턴스를 만들고 싶습니다.

어떻게할까요?

  1. 확인하려는 클래스의 문자열로 이름이 있습니다.
  2. 내가 할 수 있도록 클래스 인스턴스를 인스턴스화해야 할 것 같아요
  3. 속성을 반복하고 인쇄하십시오.


답변

레일에서는 다음을 수행 할 수 있습니다.

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> 


답변

Rails에서 매우 간단합니다 : 사용 String#constantize

class_name = "MyClass"
instance = class_name.constantize.new


답변

이 시도:

Kernel.const_get("MyClass").new

그런 다음 개체의 인스턴스 변수를 반복하려면 :

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


답변

module One
  module Two
    class Three
      def say_hi
        puts "say hi"
      end
    end
  end
end

one = Object.const_get "One"

puts one.class # => Module

three = One::Two.const_get "Three"

puts three.class # => Class

three.new.say_hi # => "say hi"

루비 2.0, 아마도 이전 버전에서는 Object.const_get것이다 재귀 조회 수행 과 같은 네임 스페이스에를 Foo::Bar. 네임 스페이스가 미리 하이라이트는 사실을 알고있을 때 위의 예는 const_get직접적으로 독점적에 반대 모듈을 호출 할 수 있습니다 Object.


답변