Help me with some nested Hashes.

D

Daniel Finnie

What I want to do is have 2 nested hashes, the outer hash returning a
new hash on an unknown key and the inner hash returning a space on an
unknown key.

For example:
values = Hash.new # as described above
values[4][4] = "H" # The 4 is an unknown key, so a new Hash is
formed # and the value of that inner hash's 4 key is "H"
values[5][6] # => " "

I got this to work correctly with the following (only ints are keys):
@value = []
0.upto(300) do |x|
@value[x] = Hash.new(" ")
end
But that is horrible.

So I've tried this:
value = Hash.new(Hash.new(" "))
But if you pass an object as the default value for a hash, it is not
cloned for each unknown key.

So then this:
value = Hash.new { Hash.new(" ") }
But that has some problems as well:
irb(main):013:0> value = Hash.new {Hash.new(" ") }
=> {}
irb(main):014:0> value[5][6] = "H"
=> "H"
irb(main):015:0> value[5][6]
=> " "
irb(main):016:0> value[5][7] = "I"
=> "I"
irb(main):017:0> value[5][6]
=> " " # It just changed from what I set it to above.


Is there anyway to get this to work?
 

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top