Proc rebinding

C

Csaba Henk

In ruby there is such a thing as rebinding a proc object, as the example
below shows:

#####
class Foo
def initialize
@name = "anna"
end
@@hello = proc{ puts "hello #{@name}" }
define_method :hello, @@hello
end

f=Foo.new
f.hello
class Foo; @@hello[]; end
####

When you run the above, it writes:

hello anna
hello

A Proc obejct carries its binding with itself (ie. is a closure), as it
is well known. When @@hello was created, it did not know any @name. But
then it was passed to define_method, and the resulting method "hello"
can find @name in the instances. That is, ruby altered the bindings of
(some kind of copy of) @@hello, and only after that has it been attached
as a method. (Or rather, the binding is altered upon instantiation?)

But all of this happened under the hood.

What do you think of an explicit way of altering method bindings? I ask
it because I could have made good use of that now (I tell the concrete
example, is someone is interested). When one works with a bunch of
anonymous processes, it's not handy/feasible to make them methods just
for getting the binding changed.

* Would it be useful?
* A few lines of C which does it?
* Is it possible with EvilRuby?
* Is something like this planned (has it been discussed)?

Csaba
 
F

Florian Gross

Csaba said:
A Proc obejct carries its binding with itself (ie. is a closure), as it
is well known. When @@hello was created, it did not know any @name. But
then it was passed to define_method, and the resulting method "hello"
can find @name in the instances. That is, ruby altered the bindings of
(some kind of copy of) @@hello, and only after that has it been attached
as a method. (Or rather, the binding is altered upon instantiation?)

[...]
* Is it possible with EvilRuby?

Yes, EvilRuby has Proc#self= which will change the self-context of a
block. Which might be a bad idea because Ruby might expect Procs to be
immutable, but I've not experienced any oddities yet. If I'm not
completely wrong this will however not change the scope of a proc
meaning it will still refer to the surrounding variables. (So the result
is a bit similar to using .instance_eval().)

Regarding methods: You can cheat there by using
obj.method:)x).unbind.force_bind(other_obj) which is also available in a
limited version in EvilRuby.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,163
Latest member
Sasha15427
Top