On 29/03/2013, at 8:32 PM, Harry Kakueki <list.push / gmail.com> 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?
>=20
> h =3D Hash.new {|x,y| x[y] =3D y}
> h2 =3D {"two"=3D>2,"three"=3D>3}
> h.merge!(h2)
> p h["two"]     #> 2
> p h["tree"]    #> "tree"
>=20
>=20
>=20
> Harry
>=20


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 =3D {}; def h.[](key); self.has_key?(key) ? super(key) : key; end

or alternatively:

h =3D {}
(class << h; self; end).send(:define_method, :[]){|key| =
self.has_key?(key) ? super(key) : key}

Julian=