From: Robert Klemme Date: 2008-03-24T07:00:01+09:00 Subject: Re: Sytem hook for instance names? On 23.03.2008 16:15, Jeff Patterson wrote: > Is there a system hook that allows a method to get an instance's symbol > from its' object id? > > i.e. > > a=SomeObject.new > SomeSystemhook(a) => :a (or "a" I suppose) > > For the curious, here's a rather long winded explanation of what I need. > > I'm writing a system simulator in ruby (think systemC). The snippet > below shows a typical invocation: > Notice that the Sim object (with all off its components) is passed to > the Simulation engine (sim) for execution. The Simulation engine uses > Kernel#ObjectSpace to find and schedule objects it needs to manage. IMHO that is bad design. The Sim instance needs to know about all objects that belong to it. You should do that within your application and not traverse all objects (of some kind). That is not very efficient and has some problems of its own (threads, multiple Sim instances etc.). > For > efficiency it flattens the netlist and extracts only the input pins and > clocked output pins it needs to manage. But for messaging, netlisting > etc, I want the sim engine to know the _name_ of the pins parent (as > opposed to its object_id) and I would also like to obviate the need to > redundantly pass the component's symbol name to its constructor. i.e. > > instead of > @d1 = Dflop.new(:d1) > > I want to be able to do: > > @d1=Dflop.new That's easily solved: Base = Struct.new :owner, :name class Sim def initialize @elements = {} end def create(name,cl,*args,&b) x = cl.new(*args,&b) x.owner = self x.name = name @elements[name] = x end # or def create2(name) x = yield x.owner = self x.name = name @elements[name] = x end def some_other_method create :d1, Dflop create2(:d1) { Dflop.new } end end > and then when the sim engine needs a human readable component name, it > somehow gets it from a system hook based on the object id. > Any help? Yes, do this yourself. As has been pointed out, there are various issues with the concept of "the name of an instance" notably that every object can have any number (including zero) references pointing to it. Kind regards robert