Including methods into blocks

ruby

Solution

You can't do this. The reason for what you're seeing is that there are two different contexts here. One is the context of the block, which closes over the context where it's defined. The other is the context of the Proc object wrapper, which is just the same as any other object context and completely unrelated to the context of the block itself.

I think the closest you'll get is to `instance_eval` the block using a context object that has the methods you want, but then the block won't have access to the `self` that existed where it was defined. It's up to you whether that makes sense for the method you want to write.

The other option is to pass the block an actual receiver for the `baz` method.

Problem

Anyone know how to get this to work if it's possible? ``` class Foo def self.go(&block) class << block include Bar end puts "Within Foo#go: #{block.methods.include? 'baz'}" block.call end end module Bar def baz puts "I'm happily in my place!" end end Foo.go { puts "Within actual block: #{methods.include? 'baz'}" baz } ``` This gets the output: ``` Within Foo#go: true Within actual block: false NameError: undefined local variable or method ‘baz’ for main:Object ``` EDIT: when I print out the block's class in Foo#go, it's Proc, but when I print it out within the Proc, it's Object. Could this be related?

Original source