difference between Hash.new and Hash.new { |h, k| h[k] = [] }
Difference between Hash.new and Hash.new { |h, k| h[k] = [] }
Hash.new:
- When using Hash.new
, the default value for the hash is set to nil
.
- This means that if a key is not found in the hash, the default value returned will be nil
.
- Here's an example:
h = Hash.new
h[:a] # This will return nil
Hash.new { |h, k| h[k] = [] }:
- When using Hash.new { |h, k| h[k] = [] }
, the default value for the hash is set to a new empty array.
- This means that if a key is not found in the hash, the default value returned will be a new empty array.
- Here's an example:
h = Hash.new { |h, k| h[k] = [] }
h[:a] # This will return an empty array: []