From: Robert Klemme Date: 2013-03-30T07:08:30+09:00 Subject: Re: Hash with default --20cf30050e8ac02d5104d917827f Content-Type: text/plain; charset=ISO-8859-1 On Fri, Mar 29, 2013 at 10:32 AM, 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} > I don't think this is a good implementation of a default value: you add items to the hash without any need because the return value of h[x] where x is not stored in the Hash does not change but you incur the overhead of storing the value in the Hash (which may include memory reallocation etc.). > h2 = {"two"=>2,"three"=>3} > h.merge!(h2) > p h["two"] #> 2 > p h["tree"] #> "tree" > What's wrong with h = Hash.new {|x,y| x[y] = y}.merge!("two"=>2, "three"=>3) ? You can even omit the brackets: h = Hash.new {|x,y| x[y] = y}.merge! "two"=>2, "three"=>3 If you have just one usage location where you need the default replacement this would be an alternative: h = {"two"=>2,"three"=>3} ... h.fetch(key) {|y| h[y] = y} Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/ --20cf30050e8ac02d5104d917827f Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable

On Fri, Mar 29, 2013 at 10:= 32 AM, 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?

h =3D Hash.new {|x,y| x[y] =3D y}

I don't think this is a good implementat= ion of a default value: you add items to the hash without any need because = the return value of h[x] where x is not stored in the Hash does not change = but you incur the overhead of storing the value in the Hash (which may incl= ude memory reallocation etc.).
=A0
h2 =3D {"two"=3D>2,"three"=3D>3}
h.merge!(h2)<= br>p h["two"]=A0=A0=A0=A0 #> 2
p h["tree"]=A0=A0= =A0 #> "tree"

What's wro= ng with

h =3D Hash.new {|x,y| x[y] =3D y}.merg= e!("two&qu= ot;=3D>2, "three"=3D>3)

? =A0You can even omit the brackets:

h = =3D Hash.new {|x,y| x[y] =3D y}.merge! "two"=3D>2, "three= "=3D>3

If= you have just one usage location where you need the default replacement th= is would be an alternative:

h<= /font>=A0=3D {"two"=3D>2,"three"=3D>3}
...
h.fetch(key) =A0{= |y| h[y] =3D y}

Kind regard= s

robe= rt

--
remember.guy do |as, often| as.yo= u_can - without end
http://blog.rubybestpractice= s.com/
--20cf30050e8ac02d5104d917827f--