Get the name of variable with which a method was approached from this class in Ruby

StackOverflow https://stackoverflow.com/questions/19453389

  •  01-07-2022
  •  | 
  •  

سؤال

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?

هل كانت مفيدة؟

المحلول

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"

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top