[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Re: Accesing the name of an instance from within an method

Tim Pease

1/30/2007 3:56:00 PM

On 1/30/07, Gerald Ebberink <g.h.p.ebberink@nclr.nl> wrote:
>
> Hi all,
>
> I am wondering if it is possible to access the name of an instance from within a method.
> What I would like to do is something similar to this
>
> class Someclass
>
> def say_hi
> puts "Hi I am" + self.name
> end
>
> end
>
> fun = Someclass.new
>
> fun.say_hi
>
>
> give the output
>
> Hi I am fun
>
>
> Kind regards,
>
> Gerald Ebberink
>

My gut reaction is to say "no, you can't do that." The say_hi method
does not know about the context of the caller and the local variables
available there.

However, take a look at Ryan Davis' ParseTree and Ruby2Ruby gems.
These allow a program to analyze its own source code. That might be
one direction to look into.

So, a reserved "maybe" is probably the best answer ;)

Ryan or Eric, any thoughts on this one?

Blessings,
TwP

1 Answer

Gavin Kistner

1/30/2007 5:08:00 PM

0

On 1/30/07, Gerald Ebberink <g.h.p.ebber...@nclr.nl> wrote:
> I am wondering if it is possible to access the name of an instance
> from within a method.
> What I would like to do is something similar to this
> class Someclass
> def say_hi
> puts "Hi I am" + self.name
> end
> end
>
> fun = Someclass.new
> fun.say_hi
>
> give the output
>
> Hi I am fun

Instances do not have names; what you have above is a variable (named
'fun') that references your instance. For example, consider this:

my_array = [ Someclass.new ]
wow = my_array[ 0 ]
my_hash = { :foo=>my_array[0] }

wow.say_hi
my_array[ 0 ].say_hi
hy_hash[ :foo ].say_hi

What would you expect that method to output?