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?
Hash.defaultis used to set the default value returned when you query a key that doesn’t exist. An entry in the collection is not created for you, just because queried it.Also, the value you set
defaultto is an instance of an object (an Array in your case), so when this is returned, it can be manipulated.