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?
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?