Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails source code : initialize hash in a weird way?

in the rails source : https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb

the following can be seen

@load_hooks = Hash.new {|h,k| h[k] = [] }

Which in IRB just initializes an empty hash. What is the difference with doing

@load_hooks = Hash.new
like image 394
npiv Avatar asked Nov 05 '11 22:11

npiv


2 Answers

Look at the ruby documentation for Hash

new → new_hash click to toggle source
new(obj) → new_hash
new {|hash, key| block } → new_hash

Returns a new, empty hash. If this hash is subsequently accessed by a key that doesn’t correspond to a hash entry, the value returned depends on the style of new used to create the hash. In the first form, the access returns nil. If obj is specified, this single object will be used for all default values. If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block’s responsibility to store the value in the hash if required. Example form the docs

# While this creates a new default object each time
h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" }
h["c"]           #=> "Go Fish: c"
h["c"].upcase!   #=> "GO FISH: C"
h["d"]           #=> "Go Fish: d"
h.keys           #=> ["c", "d"]
like image 88
topek Avatar answered Oct 29 '22 13:10

topek


The difference is in handling missing values. First one returns empty Array, second returns nil:

irb(main):001:0> a = Hash.new {|h,k| h[k] = [] }
=> {}
irb(main):002:0> b = Hash.new
=> {}
irb(main):003:0> a[123]
=> []
irb(main):004:0> b[123]
=> nil

Here is the link to documentation: http://www.ruby-doc.org/core-1.9.3/Hash.html#method-c-new

like image 39
Dawid Avatar answered Oct 29 '22 14:10

Dawid