From: Robert Dober Date: 2007-05-06T19:39:59+09:00 Subject: Re: How can I output an object/variable's name? On 5/6/07, Robert Klemme wrote: > 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. You are right Robert. As a matter of fact I have produced yet another masterpiece of "Not understanding OP's needs" :( But I really loved Rick's way to explain things. > 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? > However John I still fail to see why you were happy with "eval" why would you need it? If you feel the need for eval in this context it is for 99% wrong, maybe we can help you better if you describe a little bit more of your needs. Maybe all you need are objects with a name property and maybe it would be best to use a different name (see how the two levels that designation can be used might become *very* confusing) like e.g. how_I_call_this_object (that is an extreme example of course). Cheers Robert -- You see things; and you say Why? But I dream things that never were; and I say Why not? -- George Bernard Shaw