# Calling a block with some context

**URL:** <https://www.ruby-forum.com/t/calling-a-block-with-some-context/59379>\
**Category:** Ruby\
**Created:** [May 3, 2006, 6:59pm UTC](https://www.ruby-forum.com/t/calling-a-block-with-some-context/59379 "2006-05-03T18:59:25Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [May 3, 2006, 6:59pm UTC](https://www.ruby-forum.com/t/calling-a-block-with-some-context/59379/1 "2006-05-03T18:59:25Z")

</div>

I would like to be able to call a block / proc / lambda with the current  
context (as well as the context it was created in):

def make\_proc  
Proc.new {puts from\_calling\_context}  
end

proc = make\_proc  
from\_calling\_context = ‘Hello from the calling context’  
call\_with\_my\_context( proc )

… Something like that.

Thanks for any thoughts,  
Benjohn

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [May 3, 2006, 6:59pm UTC](https://www.ruby-forum.com/t/calling-a-block-with-some-context/59379/2 "2006-05-03T18:59:38Z")

</div>

On Tue, 2006-05-02 at 17:17 +0900, removed\_email\_address@domain.invalid wrote:

> I would like to be able to call a block / proc / lambda with the current  
> context (as well as the context it was created in):
> 
> def make\_proc  
> Proc.new {puts from\_calling\_context}  
> end
> 
> proc = make\_proc  
> from\_calling\_context = ‘Hello from the calling context’  
> call\_with\_my\_context( proc )

This is something that’s been discussed quite a bit I think, with the  
general conclusion being that it’s not possible to rebind procs like  
this.

You can emulate it up to a point, but with some potentially serious  
quirks, e.g:

require ‘facet/binding’  
require ‘ostruct’

def call\_with\_my\_context(blk)  
Binding.of\_caller do |b|  
o = OpenStruct.new  
b.local\_variables.each { |v| o.send("#{v}=", b[v]) }  
r = o.instance\_eval(&blk)  
o.methods.select { |m| m =~ /[^=]=$/ }.each { |v| v = v[0…-2]; b[v]  
= o.send(v) }  
r  
end  
end

def make\_proc  
avar = :lex\_scope  
Proc.new do |ret| # only need arg if you want to change vars outside  
the proc  
puts avar  
puts from\_calling\_context;  
ret.from\_calling\_context = ‘changed’ # such as here  
“result”  
end  
end

blk = make\_proc  
from\_calling\_context = ‘Hello from the calling context’  
puts call\_with\_my\_context(blk)  
puts from\_calling\_context

Outputs:
