I'm trying to create classes using meta-programming in Ruby as per this question: Dynamically define named classes in Ruby. Everything is going well, except it seems like in the block from Class.new
can't reference method parameters which is odd.
I have this
class A; end
module B
def self.class_with_method(class_name, method_return)
klass = Class.new(A) do
def example
method_return
end
end
B.const_set class_name, klass
end
end
But when I have the above and then test it with
B.class_with_method 'ExampleClass', 23
B::ExampleClass.new.example
Gives me
undefined local variable or method `method_return' for #<B::ExampleClass:0x00007ff1d7130d00> (NameError)
This is odd because if I were to do
def add_number(number)
[1, 2, 3, 4].map {|i| i + number}
end
add_number(2)
# => [3, 4, 5, 6]
So clearly blocks can take method arguments.
Is there a way to pass method_return
to def example
within the block?