Ruby: Unexpected result from Hash.keys in multi-dimensional hash -
i have following small sequence, makes no sense me:
irb(main):001:0> h = {} => {} irb(main):002:0> h.default = {} => {} irb(main):003:0> h["foo"]["bar"] = 6 => 6 irb(main):004:0> h.length => 0 irb(main):005:0> h.keys => [] irb(main):006:0> h["foo"] => {"bar"=>6} how is step 5 returns empty list of keys, , step 4 indicates length of h 0, yet can see in step 6 "foo" valid key , has associated value. expect keys return ["foo"], , length return 1.
what misunderstanding? note ruby 1.9.3p0
also note works correctly:
irb(main):001:0> h = {} => {} irb(main):002:0> h["foo"] = {} => {} irb(main):003:0> h["foo"]["bar"] = 6 => 6 irb(main):004:0> h.length => 1 irb(main):005:0> h.keys => ["foo"] irb(main):006:0> h["foo"] => {"bar"=>6} the difference use of hash.default set default value , skip explicit initialization of h["foo"]. bug?
you set default value returned if no value found. doesn't change fact there no value assigned h["foo"]. {"bar"=>6} value key not found.
h = {} h.default = {} # => {} h["foo"]["bar"] = 6 # => 6 h["foo"] # => {"bar"=>6} h["baz"] # => {"bar"=>6} if wanted hash returns , sets values of missing keys empty hashes, have do:
h = hash.new { |hash, key| hash[key] = {} } h["foo"]["bar"] = 6 # => 6 h # => {:foo=>{:bar=>6}}
Comments
Post a Comment