ruby - Why does my Hash not get filled when initializing with a default object -


given code:

h = hash.new([])  3.times |i|   h[:a] << end 

i expect h {:a => [0, 1, 2]}, empty. doing wrong?

as api says:

if obj specified, single object used default values.

with small rewrite of code, should become clear happens:

a = [] h = hash.new(a) 3.times { |i| h[:a] << }  # like: # 3.times { |i| << } # because `h` not respond key :a  h # => {}  # => [0, 1, 2] 

what want do, this:

h = hash.new { |h, k| h[k] = [] } 3.times { |i| h[:a] << }  h # => {:a=>[0, 1, 2]} 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -