[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Confusion About UnboundMethod

James Herdman

4/16/2006 5:07:00 AM

I'm reading the last little fragment of the Pick Ax book during my exam
study breaks right now, and I'm contemplating this UnboundMethod
hotness.

Pick Ax says, "As with aliases, unbounch methods are references to the
definition of the method at the time they are created" with the example

[CODE BEGIN]
unbound_length = String.instance_method(:length)
class String
def length
99
end
end
str = "cat"
str.length -> 99
bound_length = unbound_length.bind(str)
bound_length.call -> 3
[CODE END]

The first part of my question is if I can read "... are references to
the definition of the definition of the method at the time they are
created" as being equivalent to "copy of"? (My assumption is yes,
given that my unbound copy isn't altered by redefinition #length.)

The second part of my question what about the contents of
unbound_length. Does it actually contain code, or is it just a memory
location? (I.E. is there a way I can have unbound_length spit out the
code for #length?)

Thank you for your time,

James H.

1 Answer

Robert Klemme

4/16/2006 10:21:00 AM

0

James Herdman wrote:
> I'm reading the last little fragment of the Pick Ax book during my exam
> study breaks right now, and I'm contemplating this UnboundMethod hotness.
>
> Pick Ax says, "As with aliases, unbounch methods are references to the
> definition of the method at the time they are created" with the example
>
> [CODE BEGIN]
> unbound_length = String.instance_method(:length)
> class String
> def length
> 99
> end
> end
> str = "cat"
> str.length -> 99
> bound_length = unbound_length.bind(str)
> bound_length.call -> 3
> [CODE END]
>
> The first part of my question is if I can read "... are references to
> the definition of the definition of the method at the time they are
> created" as being equivalent to "copy of"? (My assumption is yes, given
> that my unbound copy isn't altered by redefinition #length.)

IMHO not. In the example there is an initial version of the method
"length". A reference to that is kept alive with "unbound_method".
Then there is a second version of the method created by the class body
that replaces the original def (but that is still accessible via
"unbound_length"). If you execute instance_method twice in the
beginning you get two UnboundMethod objects but both point to the same
piece of code.

> The second part of my question what about the contents of
> unbound_length. Does it actually contain code, or is it just a memory
> location? (I.E. is there a way I can have unbound_length spit out the
> code for #length?)

No. There is no standard mechanism to convert some ruby object back
into the source code. You'll have to parse the code yourself.

Kind regards

robert