Ruby: What does the line "m = Hash.new {|h,k| h[k] = []}" accomplish that "Hash.new" doesn't?
hash, rack, ruby
Solution
It allows you to define default value as an array
h = Hash.new { |h, k| h[k] = [] }
h[:a] # => {:a=>[]}
h[:b] << 123 # => {:a=>[], :b=>[123]}
More examples are here: Hash.new
Problem
While studying this Railscast I came across the following bit of source code from Rack: ``` def self.middleware @middleware ||= begin m = Hash.new {|h,k| h[k] = []} m["deployment"].concat [ [Rack::ContentLength], [Rack::Chunked], logging_middleware ] m["development"].concat m["deployment"] + [[Rack::ShowExceptions], [Rack::Lint]] m end end ``` My question is about the third line. What does passing the block `{|h,k| h[k] = []}` to `Hash.new` accomplish? I tried it in IRB and it doesn't seem to do anything different from a regular `Hash.new`: ``` 2.0.0p247 :003 > m1 = Hash.new => {} 2.0.0p247 :004 > m2 = Hash.new{|h,k| h[k] = []} => {} 2.0.0p247 :005 > m1 == m2 => true ``` ... but I'm going to guess that the guys who wrote Rack know more about Ruby than I do. What's the reasoning behind including that block?