使用变量动态定义类

时间:2014-05-08 12:53:42

标签: ruby metaprogramming

我想动态定义几个ruby类。这些类应该有自定义名称,它们应该包含保存自定义内容的方法。基本上我正在尝试以下内容,但变量the_address似乎(原因)超出了范围。有没有办法做到这一点?

{'SomeName'=> 'some_address', 'SomeOtherName' => 'some_other_address'}.each do |name, the_address|
  Object.const_set(name, 
    Class.new() do
      def address
        the_address
      end
    end
  )
end

问题是:

SomeName.new.address
#=> NameError: undefined local variable or method `the_address' for #<SomeName:0x007fa6ba9a6d08>

1 个答案:

答案 0 :(得分:2)

您可以使用define_method保持相同的范围:

{'SomeName'=> 'some_address', 'SomeOtherName' => 'some_other_address'}.each do |name, the_address|
  klass = Class.new() do
    define_method(:address) do
      the_address
    end
  end
  Object.const_set(name, klass)
end
SomeName.new.address
# => "some_address"