Rails source code: initialize hash in weird mode?

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

it's clear that

@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
+5
source share
2 answers

Check out the ruby documentation for Hash

new โ†’ new_hash click to switch the source
new (obj) โ†’ new_hash
new {| hash key | block} โ†’ new_hash

. , -, , . nil. obj , . , - . , .

# 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"]
+4

. Array, 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

: http://www.ruby-doc.org/core-1.9.3/Hash.html#method-c-new

+4
source

All Articles