Question

I want to define a couple of ruby classes dynamically. The classes should have custom names and they should include methods holding custom content. Basically i'm trying the following, but the variable the_address seems (of cause) to be out of scope. Is there any way to do this?

{'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

And the problem:

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

Solution

You can use define_method to remain at the same scope:

{'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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top