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.
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.
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.
Daniel
I was beat to it, but since I spent ten minutes figuring it out, here
is my solution anyway
require ‘rubygems’
require ‘spec’
a subclass, instead of a re-opened base class… how un-rubyish
class SpaceHash < Hash
def
value = super(key)
value = self[key] = Hash.new(" ") unless value
value
end
end
context “SpaceHash” do
setup do @space_hash = SpaceHash.new @space_hash[5][6] = “H”
end
specify “unassigned keys return a space” do @space_hash[5][5].should == " "
end
specify “assigned keys should return their value” do @space_hash[5][6].should == “H”
end
specify “assigned another key to the second layer should not
reassign othe keys” do @space_hash[5][7] = “I” @space_hash[5][6].should == “H”
end
end