How do I tell an object to register “itself” with a hash that has been
passed in during initialization?
For example, I have:
START ---------------------------
hashOfHomes = {}
Class House
def initialize homeAddress, homeHash @localHomeAddressString = homeAddress
HOW DO I PUSH “THIS” OBJECT (i.e. “SELF”) ONTO THE HASH DURING THIS
INITIALIZATION???
end
end
home = House.new( “123 Main Street”, hashOfHomes)
END ---------------------------
I’ve read through multiple references on object creation and “self” but
don’t see anything that is a clear answer.
Thanks, in advance, for any assistance you can offer!
hash = {}
=> {}
class A
def initialize(n, hash)
hash.merge! n => self
end
end
=> nil
A.new(1, hash)
=> #<A:0x007f90b3159d20>
hash
=> {1=>#<A:0x007f90b3159d20>}
Hash doesn’t have any ‘push’ method (this is for Array).
homeHash[@localHomeAddressString] is probably returning ‘nil’
because this key doesn’t have any value associated with it. After
that, ruby tries to send ‘push’ method to this returned object.
This is how I do it and it works fine. Notice that I do not do the
registration while initialising the object but with another method. This
is because (as far as I understand) while the initialise method is
executed by the object generator of the class, the object was not
actually created yet.
def onstream(stream_object,pond_label)
raise “#{pond_label} already used. Must be unique\n” unless
(stream_object.pond_registry[pond_label].nil?)
Thanks for all your help. I’ve learned about multiple options from each
of you that have me thinking about multiple solution permutations that
will work for what I’m trying to do.
Ultimately, I need each new object of a certain class type to register
itself with a centralized Hash construct, using a unique address key, so
that I can access any one of the objects, later, by the address key.
With your help, I can do that, now. I appreciate your efforts!
This is how I do it and it works fine. Notice that I do not do the
registration while initialising the object but with another method. This
is because (as far as I understand) while the initialise method is
executed by the object generator of the class, the object was not
actually created yet.
No: the object is already created (allocated). The initialize method
is there for you to set it up as desired, but ‘self’ is a completely
formed object and it can call its own methods during initialize, and/or
pass itself to other objects.
Whether this is a good design practice is another issue; it may make
your objects less reusable if they are forcibly linked to a single
container object.
Another option is to use a method of the container to create and add the
objects: this lets you create free objects, and/or objects in distinct
containers.
class Container
def initialize @collection = {}
end
def create_foo(id, *args) @collection[id] = Foo.new(*args)
end
end