From: Robert Klemme Date: 2008-12-11T17:10:40+09:00 Subject: Re: why Hash corrupts 'key' object ? 2008/12/11 Dmitry Perfilyev : > Hi, I have next script: > t.rb: > =========================== > class TestStr < String > attr_accessor :dupstr > def initialize ( str ) > @dupstr = str > super(str) > end > end > ts=TestStr.new("aaa") > puts ts.dupstr > h=Hash.new() > h[ts]=true > puts h.keys.first.class > puts h.keys.first > puts h.keys.first.dupstr > =========================== > > run it: > > $ ruby t.rb > aaa > TestStr > aaa > nil > $ > > The question is - why there is 'nil' in the last line instead of "aaa" ? Because Hash copies #dup an unfrozen String. http://www.ruby-doc.org/core/classes/Hash.html#M002878 Try this: class TestStr < String attr_accessor :dupstr def initialize ( str ) @dupstr = str super(str) end end ts=TestStr.new("aaa") puts ts.dupstr, ts.object_id h=Hash.new() h[ts]=true puts h.keys.first.class, h.keys.first, h.keys.first.object_id, h.keys.first.dupstr puts "----" ts.freeze puts ts.dupstr, ts.object_id h=Hash.new() h[ts]=true puts h.keys.first.class, h.keys.first, h.keys.first.object_id, h.keys.first.dupstr It is generally a bad idea to inherit core classes. Delegation is much better (see Mike's reply). Cheers robert -- remember.guy do |as, often| as.you_can - without end