tricky hash initialization

R

Ray Pereda

h = Hash.new {|h,k| h[k] = {} }

This is one level deep defaults to a fresh new hash.

h = Hash.new {|h,k| h[k] = Hash.new{ |h2,k2| h2[k2] = {} } }

This is two levels deep initialization to a fresh new hash.

How do I this for arbitrarily deep hashes?

h["a"]["b"]["c"] = 3 #=> {"c"=>3}

I'm using this to build very clean implementations of state machine
building algorithms.

Your help is very much appreciated.

-Ray
 
R

Ray Pereda

Sebastian said:
Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}

Thanks for the attempt. Seems on the right track but not quite.
h = Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)} => {}
h["a"]["b"]["c"] => {}
h
=> {"c"=>{}}

After h["a"]["b"]["c"]
what needs to happen is h is equal to
{"a"=>{"b"=>{"c"=>{}}}}

Appreciating the Ruby Community's Help,
Ray
 
M

Mikael Høilund

D

David A. Black

Hi --

Sebastian said:
Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}

Thanks for the attempt. Seems on the right track but not quite.
h = Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)} => {}
h["a"]["b"]["c"] => {}
h
=> {"c"=>{}}

After h["a"]["b"]["c"]
what needs to happen is h is equal to
{"a"=>{"b"=>{"c"=>{}}}}

I think it's a variable clobbering issue. Try this:

hash = Hash.new {|h,k| h[k] = Hash.new(&h.default_proc) }


David
 
D

David A. Black

I should add: the same-variable-name version works in Ruby 1.9.


David

Hi --

Sebastian said:
Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}

Thanks for the attempt. Seems on the right track but not quite.
h = Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)} => {}
h["a"]["b"]["c"] => {}
h
=> {"c"=>{}}

After h["a"]["b"]["c"]
what needs to happen is h is equal to
{"a"=>{"b"=>{"c"=>{}}}}

I think it's a variable clobbering issue. Try this:

hash = Hash.new {|h,k| h[k] = Hash.new(&h.default_proc) }


David

--
Rails training from David A. Black and Ruby Power and Light:
* Advancing With Rails August 18-21 Edison, NJ
* Co-taught by D.A. Black and Erik Kastner
See http://www.rubypal.com for details and updates!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top