If a class has built checks and raises an exception if it finds
something wrong, how can I tell which instance had the error? I know
there's an object_id, but can I know the name of the objects own
instance variable?
If a class has built checks and raises an exception if it finds
something wrong, how can I tell which instance had the error? I know
there's an object_id, but can I know the name of the objects own
instance variable?
<snip />
Also, can an instance know his 'path' from the top-level?
<snip />
No and no (at least, no sensible way). You are dealing with
symbolic names 'huey' versus actual references and objects.
The 'proper' way is to have the object know its name:
If a class has built checks and raises an exception if it finds
something wrong, how can I tell which instance had the error? I know
there's an object_id, but can I know the name of the objects own
instance variable?
These are examples of binding an instance to a particular key (think of it in terms of a dictionary/hashtable), and not naming the instances of Nephew: huey, duey and luey.
You can identify an object by its object_id. Variables are just
references to an object with a convenient name for your use. If you
want to give an object an actual name, you have to pass it in as a
parameter on construction.
Geoff Barnes wrote:
···
If a class has built checks and raises an exception if it finds
something wrong, how can I tell which instance had the error? I know
there's an object_id, but can I know the name of the objects own
instance variable?
It is sort of possible to find out someone's name. The following of course, is easily breakable.
% cat names.rb
class Nephew
def name(&block)
names_objects = eval("local_variables.inject({}){ |h, k| h[k] = eval(k); h}", block)
names_objects.find { |k, v| v.object_id == object_id }.first
end
end
On Sep 5, 2006, at 8:30 AM, Timothy Goddard wrote:
You can identify an object by its object_id. Variables are just
references to an object with a convenient name for your use. If you
want to give an object an actual name, you have to pass it in as a
parameter on construction.
Geoff Barnes wrote:
If a class has built checks and raises an exception if it finds
something wrong, how can I tell which instance had the error? I know
there's an object_id, but can I know the name of the objects own
instance variable?