From eb954f44e53ba18225a0e906891c47373ce0d651 Mon Sep 17 00:00:00 2001 From: ko1 Date: Thu, 20 Dec 2007 08:20:02 +0000 Subject: * proc.c: support Proc#binding. * sample/test.rb: add a test. git-svn-id: http://svn.ruby-lang.org/repos/ruby/trunk@14360 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- proc.c | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'proc.c') diff --git a/proc.c b/proc.c index e75a90706..a3dcc0c97 100644 --- a/proc.c +++ b/proc.c @@ -1459,6 +1459,40 @@ localjump_reason(VALUE exc) return rb_iv_get(exc, "@reason"); } +/* + * call-seq: + * prc.binding => binding + * + * Returns the binding associated with prc. Note that + * Kernel#eval accepts either a Proc or a + * Binding object as its second parameter. + * + * def fred(param) + * proc {} + * end + * + * b = fred(99) + * eval("param", b.binding) #=> 99 + * eval("param", b) #=> 99 + */ +static VALUE +proc_binding(VALUE self) +{ + rb_proc_t *proc; + VALUE bindval = binding_alloc(rb_cBinding); + rb_binding_t *bind; + + GetProcPtr(self, proc); + GetBindingPtr(bindval, bind); + + if (TYPE(proc->block.iseq) == T_NODE) { + rb_raise(rb_eArgError, "Can't create Binding from C level Proc"); + } + + bind->env = proc->envval; + bind->cref_stack = proc->special_cref_stack; + return bindval; +} /* * Proc objects are blocks of code that have been bound to @@ -1497,6 +1531,7 @@ Init_Proc(void) rb_define_method(rb_cProc, "hash", proc_hash, 0); rb_define_method(rb_cProc, "to_s", proc_to_s, 0); rb_define_method(rb_cProc, "lambda?", proc_lambda_p, 0); + rb_define_method(rb_cProc, "binding", proc_binding, 0); /* Exceptions */ rb_eLocalJumpError = rb_define_class("LocalJumpError", rb_eStandardError); -- cgit