hash of hashes by default

B

Belorion

I want a Hash of Hashes. Furthermore, I want it so that if a key for
the first has does not exist, the default value is a new hash. It's
simple enough to do a has_key? on a hash to see if it already exists,
but it seems like there might be a trick to it that I'm not aware of.

So, instead of

foo =3D Hash.new

mylist.each do |ii|
anotherlist.each do |jj|
if foo.has_key?( ii )
foo[ii][jj] =3D "hello world"
else
foo[ii] =3D { jj =3D> "hello world" }
end
end
end

I can do:

mylist.each do |ii|
anotherlist.each do |jj|
foo[ii][jj] =3D "hello world"
end
end

Any suggestions?
 
J

James Edward Gray II

I want a Hash of Hashes. Furthermore, I want it so that if a key for
the first has does not exist, the default value is a new hash.

irb(main):001:0> foo = Hash.new { |hash, key| hash[key] = Hash.new }
=> {}
irb(main):002:0> foo["ii"]["jj"] = "Hello World."
=> "Hello World."
irb(main):003:0> foo["ii"]
=> {"jj"=>"Hello World."}
irb(main):004:0> foo["ii"]["jj"]
=> "Hello World."

Hope that helps.

James Edward Gray II
 
A

Austin Ziegler

I want a Hash of Hashes. Furthermore, I want it so that if a key
for the first has does not exist, the default value is a new
hash.
irb(main):001:0> foo =3D Hash.new { |hash, key| hash[key] =3D Hash.new }
=3D> {}
irb(main):002:0> foo["ii"]["jj"] =3D "Hello World."
=3D> "Hello World."
irb(main):003:0> foo["ii"]
=3D> {"jj"=3D> "Hello World."}
irb(main):004:0> foo["ii"]["jj"]
=3D> "Hello World."
=20
An infinite variation of this is a two liner.

hinit =3D proc { |hash, key| hash[key] =3D Hash.new(&hinit) }
foo=09=3D Hash.new(&hinit)

foo["ii"]["jj"]["kk"] =3D "Hi, James!"

require 'pp'
p foo

-austin
--=20
Austin Ziegler * (e-mail address removed)
* Alternate: (e-mail address removed)
 
B

Belorion

On Jun 16, 2005, at 11:07 AM, Belorion wrote:
=20
I want a Hash of Hashes. Furthermore, I want it so that if a key for
the first has does not exist, the default value is a new hash.
=20
irb(main):001:0> foo =3D Hash.new { |hash, key| hash[key] =3D Hash.new }
=3D> {}
irb(main):002:0> foo["ii"]["jj"] =3D "Hello World."
=3D> "Hello World."
irb(main):003:0> foo["ii"]
=3D> {"jj"=3D>"Hello World."}
irb(main):004:0> foo["ii"]["jj"]
=3D> "Hello World."
=20
Hope that helps.

Aha! Perfect!
 

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

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,157
Latest member
MercedesE4
Top