5

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

2 Answers 2

4

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"]
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.