Is it possible to have a class method that prints the name of the variable its parent class is assigned to? Example:
class Test
def who_am_I_assigned_to
puts "#{??}"
end
end
THIS = Test.new
THIS.who_am_I_assigned_to
# >> THIS
Is it possible to have a class method that prints the name of the variable its parent class is assigned to? Example:
class Test
def who_am_I_assigned_to
puts "#{??}"
end
end
THIS = Test.new
THIS.who_am_I_assigned_to
# >> THIS
But you'd have to recursively search through all the instance_variables of every object. And, as Cary points out, an object can be assigned to more than one variable at a time.
The reason I was looking for this behavior was to use the variable name but also as a position within a grid of data. So if had a 2 dimensional Grid the variable names would be like "AA", "AB", "BC", etc. It is knew its name it would also know its position.
What you're describing is an "action at a distance" anti-pattern where changes to one part of a program change another part of a program with no obvious connection. This violates encapsulation; good encapsulation allows you to understand a single piece of a system by just looking at its inputs and outputs. Violating encapsulation means in order to understand one part of the system you have to understand every part of the system leading to a maintenance nightmare. Modern languages and practices strive to avoid this as much as possible.
For example, a variable's name should never matter to the behavior of the program. You should be able to safely perform a Rename Variable refactoring to name a variable according to what makes sense to the user of the object. In your example this would alter the behavior of the program violating the Principle of Least Astonishment.
Instead you'd have an object to represent your Grid and this would manage the relationships between Nodes in the Grid. Rather than passing around individual Nodes you'd pass around the Grid.
Or each Node can know who their neighboring Nodes are. An example of this would be a traditional Tree, Graph, or Linked List structure. The advantage here is there is no fixed position and the data structure can grow or shrink in any direction. Any Node can be passed around and it knows its position within the structure.