KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I thought I understood what the default method does to a hash... Give a default value for a key if it doesn't exist: irb(main):001:0> a = {} => {} irb(main):002:0> a.default = 4 => 4 irb(main):003:0> a[8] => 4 irb(main):004:0> a[9] += 1 => 5 irb(main):005:0> a => {9=>5} All good. But if I set the default to be a empty list, or empty hash, I don't understand it's behaviour at all .... irb(main):001:0> a = {} => {} irb(main):002:0> a.default = [] => [] irb(main):003:0> a[8] << 9 => [9] # great! irb(main):004:0> a => {} # ?! would have expected {8=>[9]} irb(main):005:0> a[8] => [9] # awesome! irb(main):006:0> a[9] => [9] # unawesome! shouldn't this be [] ?? I was hoping/expecting the same behaviour as if I had used the ||= operator... irb(main):001:0> a = {} => {} irb(main):002:0> a[8] ||= [] => [] irb(main):003:0> a[8] << 9 => [9] irb(main):004:0> a => {8=>[9]} irb(main):005:0> a[9] => nil Can anyone explain what is going on?
Tags (comma-separated)
Save Edits
Cancel