3

After playing with with creating some new hash values I came across this Ruby weirdness... can anyone explain what is happening?

irb(main):001:0> some_hash = Hash.new({})
=> {}
irb(main):002:0> some_hash[:foo][:bar] = :baz
=> :baz
irb(main):003:0> some_hash
=> {}
irb(main):004:0> some_hash.keys
=> []
irb(main):005:0> some_hash[:foo]
=> {:bar=>:baz}
irb(main):006:0> some_hash.size
=> 0
irb(main):007:0> some_hash[:some_completely_new_key]
=> {:bar=>:baz}
Mladen Jablanović
  • 43,461
  • 10
  • 90
  • 113
Paul Danelli
  • 994
  • 1
  • 15
  • 25
  • I am kinda disagree, that the answer is exactly the same, since it involves “strange disappearing of `:foo` key,” which is not covered by the answer linked. – Aleksei Matiushkin Jan 27 '16 at 17:17
  • 1
    The glitch is here: `some_hash[:foo][:bar] = :baz`. You _did not assign the value_ of `some_hash[:foo]`. Call to `some_hash[:foo]` returned a default for this hash, you updated this hash successfully, but the initial hash was never updated, e. g. `some_hash#[]=` was never called. `some_hash[:foo]` in line 5 again returned the default, not the [inexisting] value of key `:foo` of `some_hash`. – Aleksei Matiushkin Jan 27 '16 at 17:18
  • 2
    Also: http://stackoverflow.com/questions/1822021/why-does-hash-new-hide-hash-members It covers the disappearance issue, and yet it's marked as a duplicate of a _later_ question. Weird. :) – Mladen Jablanović Jan 27 '16 at 17:24
  • @MladenJablanović the latter link makes much more sense, thanks. – Aleksei Matiushkin Jan 27 '16 at 17:26
  • Welcome to Stack Overflow. When asking a question, come up with a title that explains what the question is about. "Ruby Hash Weirdness. Can someone tell me what's going on here?" isn't very useful. Read "[ask]" and the "Question title" section of http://tinyurl.com/stack-hints, well, read all that article too as it's very good information. – the Tin Man Jan 27 '16 at 18:57
  • Thanks for the tip. Can you think of a better title for this Ruby Hash Weirdness as an example? I'd be very grateful for the advise from such an esteemed member of the community. – Paul Danelli Jan 28 '16 at 11:40

0 Answers0