[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Proc rebinding

Csaba Henk

1/28/2005 11:46:00 PM

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
1 Answer

Florian Gross

1/29/2005 12:06:00 AM

0

Csaba Henk wrote:

> 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.