2

I am a bit puzzled on why this piece of code does not work:

def create(type)
  Module.new do
    def foo
      type
    end
  end
end

When calling foo on the returned Module, type is not defined. Am I supposed to use a Proc or a lambda to capture the scope within the create method?

(I probably have done too much JavaScript recently)

tl;dr
How can I create Module at runtime with methods that use variables available at the time of creation?

1 Answer 1

6

type is a local variable. Well, technically, it is a parameter, but parameters behave identically to local variables.

Local variables are local to the scope they are defined in, that's why they are called "local" variables: type is defined inside the create method, it is not defined inside the foo method.

There are 4 local variables scopes in Ruby:

  • script
  • module / class definition
  • method definition
  • block

Of these four, only block scopes nest, the others create new scopes. So, if you want to use variables from an outer scope, you must use a block.

Thankfully, there is a method to define a method that takes a block, and it is aptly named Module#define_method:

def create(type)
  Module.new do
    define_method(:foo) do
      type
    end
  end
end

By the way: the assignment to m was unnecessary.

1
  • Thanks a lot for the solution but mostly for the explanation! I'll remember only blocks capture their outer scope ;)
    – Balzard
    Mar 5, 2017 at 17:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.