From: Julian Leviston Date: 2013-03-30T00:53:33+09:00 Subject: Re: Hash with default On 30/03/2013, at 2:45 AM, Julian Leviston wrote: > On 29/03/2013, at 8:32 PM, Harry Kakueki wrote: > >> I would like to make a hash like h2 with the default described by h in one line when I create the hash instead of 3 lines and 2 hashes like I did here. >> Any ideas? >> >> h = Hash.new {|x,y| x[y] = y} >> h2 = {"two"=>2,"three"=>3} >> h.merge!(h2) >> p h["two"] #> 2 >> p h["tree"] #> "tree" >> >> >> >> Harry >> > > > You *can* set a default... but you can't set the default to be a piece of code that can change default behaviour. By the way, the first line of your program doesn't work. You know that, right? > > To get what you want, you can do this: > > h = {}; def h.[](key); self.has_key?(key) ? super(key) : key; end > > or alternatively: > > h = {} > (class << h; self; end).send(:define_method, :[]){|key| self.has_key?(key) ? super(key) : key} > > Julian Sorry, forgot to set your data in there, too: h = {"two"=>2,"three"=>3}; def h.[](key); self.has_key?(key) ? super(key) : key; end There you go. Not really on one line, but oh well, you wanted different behaviour than the default hash behaviour for defaults. Julian