Variable name to string

I would like to get the name of the variable in string form, any way
this is
possible?

var = 5
puts var.foo #Want this ti put var

i looked into trying to do var.object_id.id2name but some reason this
gave
me nil, since if it is bugged or object_id is not returning the correct
object id.

Reuben

reuben doetsch wrote:

I would like to get the name of the variable in string form, any way
this is
possible?

No.

var = 5
puts var.foo #Want this ti put var

Variables are not objects. Methods operate on objects. Your .foo
operates on 5 (the object your variable ‘foo’ references), not on ‘var’.
For that reason it can’t work.

i looked into trying to do var.object_id.id2name but some reason this
gave me nil, since if it is bugged or object_id is not returning the correct
object id.

What should it give you if your object is referenced by multiple
variables?
But it won’t work anyway for the above stated reason.

Regards
Stefan

On Sep 27, 4:50 pm, reuben doetsch [email protected] wrote:

object id.

Reuben

I don’t think I quite understand why you need this. But this does
what you’re asking for (although, it’s a little hacky). See section
8.6 in The Ruby P.ming Language by Flanagan and Matz for more.

cms@mvb cat t.rb
class Object
def get_name
line_number = caller[0].split(‘:’)[1].to_i
line_exectued = File.readlines(FILE)[line_number-1]
line_exectued.match(/(\S+).get_name/)[1]
end
end

abracadabra = 3

puts abracadabra.get_name
cms@mvb ruby t.rb
abracadabra
[~]
cms@mvb

Although, since you’re able, apparently, to ask for var.foo, I’d
suggest just putting var in quotes instead of appending ‘.foo’.

Chris

but if you write

puts (abracadabra -= 2).get_name

the result won’t be the one you’re looking for :slight_smile:

reuben doetsch wrote:

I would like to get the name of the variable in string form, any way
this is
possible?

var = 5
puts var.foo #Want this ti put var

Well, you can do this the other way round:

varname = “foo”
eval("#{varname} = 5")
puts varname

But you almost certainly don’t want to do this. This is abuse of both
local variables and eval, and it means you’re solving the wrong problem,
or solving the problem in the wrong way.

Things you might reasonably do dynamically are:

  • invoke methods on an object

obj = “hello”
meth = “upcase”
p obj.send(meth) # “HELLO”

  • set and read instance variables of an object

obj = Object.new
ivar = “@foo
obj.instance_variable_set(ivar, 5)
p obj.instance_variable_get(ivar) # 5

  • locate a constant or class by name

klassname = “String”
klass = Object.const_get(klassname)
obj = klass.new
p obj # “”

  • add methods in a module to an object

module Foo
def double
self * 2
end
end
obj = “hello”
obj.extend Foo
p obj.double # “hellohello”

  • define new methods in a class or an object

Leave this one until you know the language more deeply :slight_smile: