From: Samuel Smith Date: 2010-04-05T23:34:50+09:00 Subject: Nested hash Hello All. Sample code: class NestedHash < Hash attr_accessor :val alias :to_str :to_s @val=0 def initialize blk = lambda {|h,k| h[k] = NestedHash.new(&blk)} super(&blk) end def []= (key,value) if value.is_a?(NestedHash) super(key,value) else self[key].val=value; end end end test=NestedHash.new(); test['1']='11' test['1']['2']='12' test['1']['3']='13' test['2']['4']='24' s=test['1'].val #s='11' Work as expected. In C++ by using typecast overloading it is possible to implement class that will work that way: s=test['1']# s='11' Is it possible to implement same functionality in Ruby? I've tried: alias :to_s :to_str def to_str @val end But first of all result values are wrong and i can't understand why. Secondly it works only in constructions like that: s=" "+test['1'] # ie i must tell Ruby that i need string result but not in s=test['1'] # if it were possible to tell Ruby that it use string result by default Any other suggestions? -- Posted via http://www.ruby-forum.com/.