Luk M. wrote in post #990967:
But i can get object_id:
class String
def get_id
puts self.id
puts self.object_id
end
end
Sure, the object_id is basically the object reference. It’s a property
of the object itself, not of any variable which contains a reference to
that object.
In ruby, variables are not objects.
Is it realy to get name by ID?
That question doesn’t parse.
If you’re asking “Is it really impossible to get the name of the
variable which holds a particular object_id”, then I already said yes,
and explained why. Consider these cases:
“string”.get_my_name # what should it return??
a = “some string”
@b = a
$c = a
a.get_my_name # what should it return??
h = {:foo => “another string”}
h[:foo].get_my_name # what should it return??
In any case, with closures, the same local variable can exist multiple
times with different values. e.g.
def make_adder(n)
lambda { |x| x+n }
end
a1 = make_adder(1)
a2 = make_adder(100)
puts a1.call(1) # 2
puts a2.call(1) # 101
The local variable ‘n’ has two different values in the two closures.
If you really want to update a local variable remotely, then you can
look at the ‘Binding’ class - but I think you really don’t. You have to
pass the binding explicitly, and then use ‘eval’ to access a local
variable within that binding.
DON’T DO THIS!
def increment(var, b)
eval “#{var} += 1”, b
end
a = 10
increment(“a”, binding)
puts a # 11
Local variables are not supposed to be abused this way. It’s more
reasonable to do this with instance variables (which means you should be
thinking about encapsulating long-lived state in objects, not in local
variables).
def increment(var)
instance_variable_set(var, instance_variable_get(var) + 1)
end
@a = 20
increment(:@a)
puts @a # 21
But in most sane applications, you’d use accessor methods on the object
being passed, not mess around with instance variables directly.