From: Robert Klemme Date: 2007-05-06T19:10:04+09:00 Subject: Re: How can I output an object/variable's name? On 05.05.2007 23:19, John Joyce wrote: > > On May 6, 2007, at 6:06 AM, Robert Dober wrote: > >> On 5/5/07, John Joyce wrote: >>> Suppose I have an object : >>> >>> a = 3 >>> >>> I want to output the name a and the contents 3 >>> Outputing the contents is no problem. >>> Is there a method to output the name of the variable (object) >> >> No there is no way to output the name of a variable as a variable is >> one of the view concepts in Ruby that are not directly accessible from >> inside Ruby. >> When it comes to objects things change of course, some objects have >> name properties as e.g. classes >> >> irb(main):002:0> A=Class.new >> => A >> irb(main):003:0> A.name >> => "A" >> But be aware that it is the object and not the constant referring to >> it who has the name, as one can easily see... >> irb(main):007:0* b = Class.new >> => # >> irb(main):008:0> b.name >> => "" >> irb(main):009:0> C = b >> => C >> irb(main):010:0> C.name >> => "C" >> irb(main):011:0> b.name >> => "C" >> >> this is maybe a little bit confusing but that is what ruby does when a >> class object is assigned to a constant. >> >> Robert > Thanks Robert, but... > > That is totally confusing. > So what you are saying is that some objects have names and some do not. > Since everything (almost) is an object, which objects or which classes > would have names? No, he is saying that there are classes whose instances have a property called "name". But this has absolutely nothing to do with variable names. If you think about it for a moment, it does not really make sense to want to get a variable name from an object. Consider a = b = Object.new Now, there is just one instance - which "name" would you like to get? > Oh, maybe I should go to bed. it's 6:20am here in Japan. Sleep always helps. :-) > What about injecting my own name properties into a class, could I do > this type of injection in a code block? I am not sure what you mean by "injection". But you can set instance variables - if you wish so. But you might run into trouble if you overwrite a property that's crucial for the instance. Look at instance_variables and *set and *get. Kind regards robert