0

I want to get the name of variable with which class was approached IN the method of the class. Like that:

class Object
  def my_val
    "#{???} = '#{self.to_s}'"
  end
end

a1 = "val1"
a1.my_val # = a1 = 'val1'
a2 = "val2"
a2.my_val # = a2 = 'val2' 

Can I do it?

Tolsi
  • 656
  • 9
  • 20

2 Answers2

3

An object has no idea what variable it may or may not be stored in, and in many cases this is a completely meaningless concept.

What would you expect to happen here?

ref = Object.new
another_ref = ref
@ref = another_ref
hash = { key: @ref }
array = [ hash[:key] ]
array[0].my_val
# => ...?

There are so many ways to reference an object. Knowing which name is being used is irrelevant.

In general terms, variables are just references that are given an arbitrary name that shouldn't matter to the object in question.

What you can do is provide context:

my_var = "test"
my_var.my_val(:my_var)
# => my_var="test"

Implemented as:

def my_var(name)
  "#{name}=#{self.inspect}"
end

You can also roll this up a little and be clever about it:

def dump_var(name)
  "%s=%s" % [ name, instance_variable_get(:"@#{name}").inspect ]
end

Then:

@foo = "test"
dump_var(:foo)
# => foo="test"
tadman
  • 208,517
  • 23
  • 234
  • 262
  • I knew that Ruby is good of meta-programming, I thought that this could be real. I like your dump_var method, thanks! – Tolsi Oct 18 '13 at 16:52
  • Ruby gives you a lot of reflection capabilities, but some things are not easily exposed. Back-tracing to all the references to an object is one of those things that's theoretically possible, but also not easy. – tadman Oct 18 '13 at 19:16
0

I think the short answer is "NO, you can't :/".

For Ruby (and most languages) the variable name has no meaning. The only one who can give you a hint about variable names is the compiler, and it is in a whole other abstraction level than inside Ruby.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
ichigolas
  • 7,595
  • 27
  • 50