I
Iñaki Baz Castillo
Hi, let's suppose this simple code in which I add internal attributes
to String instances and use such String objects as Hash keys:
------------------------------------------------
h =3D {}
k1 =3D "aaa"
k1.instance_variable_set name, "Aaa-011"
k2 =3D "bbb"
k2.instance_variable_set name, "Bbb-268"
h[k1] =3D "Hello"
h[k2] =3D "Bye"
------------------------------------------------
Now I want to lookup in the hash the element whose key matches "aaa"
(using String#eql?):
h["aaa"]
=3D> "Hello"
But I don't want just to get the key associated value ("Hello"), but
also the key object itself (not the "aaa" I passed but k1 object) so I
can check its @name attribute. And I need it in a very efficient way.
However I've realized right now that it's not possible. The hash key
doesn't store the given key as a reference to such object:
-------------------------------------------
puts k1.object_id
=3D> 18140060
puts k2.object_id
=3D> 16245980
h.keys.each {|k| puts k.object_id}
=3D> 16182220
=3D> 20359940
------------------------------------------.
I've realized of it while writting this mail, so forget the previous
question. Now I have another question:
--------------------
myobject =3D MyCustomClass.new
@h =3D {}
@h[myobject] =3D "lalalala"
--------------------
In this case, will Ruby GC delete myobject? or will it remain alive as
it has been used as a key of a hash (which is not GC'd in a supposed
code)?
Thanks a lot.
--=20
I=C3=B1aki Baz Castillo
<[email protected]>
to String instances and use such String objects as Hash keys:
------------------------------------------------
h =3D {}
k1 =3D "aaa"
k1.instance_variable_set name, "Aaa-011"
k2 =3D "bbb"
k2.instance_variable_set name, "Bbb-268"
h[k1] =3D "Hello"
h[k2] =3D "Bye"
------------------------------------------------
Now I want to lookup in the hash the element whose key matches "aaa"
(using String#eql?):
h["aaa"]
=3D> "Hello"
But I don't want just to get the key associated value ("Hello"), but
also the key object itself (not the "aaa" I passed but k1 object) so I
can check its @name attribute. And I need it in a very efficient way.
However I've realized right now that it's not possible. The hash key
doesn't store the given key as a reference to such object:
-------------------------------------------
puts k1.object_id
=3D> 18140060
puts k2.object_id
=3D> 16245980
h.keys.each {|k| puts k.object_id}
=3D> 16182220
=3D> 20359940
------------------------------------------.
I've realized of it while writting this mail, so forget the previous
question. Now I have another question:
--------------------
myobject =3D MyCustomClass.new
@h =3D {}
@h[myobject] =3D "lalalala"
--------------------
In this case, will Ruby GC delete myobject? or will it remain alive as
it has been used as a key of a hash (which is not GC'd in a supposed
code)?
Thanks a lot.
--=20
I=C3=B1aki Baz Castillo
<[email protected]>