Memoize

BasicWerk   EC Support   Technique   Facebook  

20140905125050_ruby_hash

ruby_hash

 

 
[29] pry(main)> h = {a: {aa: :foo}, b: {aa: :foo2}}
=> {:a=>{:aa=>:foo}, :b=>{:aa=>:foo2}}
 
[30] pry(main)> h[:a][:aa]
=> :foo
 
[31] pry(main)> h[:a][:bb] = :foo3
=> :foo3
 
[32] pry(main)> h
=> {:a=>{:aa=>:foo, :bb=>:foo3}, :b=>{:aa=>:foo2}}
 
[33] pry(main)> h[:a][:bb]
=> :foo3
 
[34] pry(main)> h[:b][:aa]
=> :foo2
 
[35] pry(main)> h[:c] = {aa: :foooo}
=> {:aa=>:foooo}
 
[36] pry(main)> h[:c][:aa]
=> :foooo
 
[37] pry(main)> h[:d]
=> nil
 
# ここがポイント
[38] pry(main)> h[:d] = {}
=> {}
 
[39] pry(main)> h
=> {:a=>{:aa=>:foo, :bb=>:foo3}, :b=>{:aa=>:foo2}, :c=>{:aa=>:foooo}, :d=>{}}
 
# エラーにならずにペアを挿入できる
[40] pry(main)> h[:d][:aa] = :baz
=> :baz
 
[41] pry(main)> h
=> {:a=>{:aa=>:foo, :bb=>:foo3}, :b=>{:aa=>:foo2}, :c=>{:aa=>:foooo}, :d=>{:aa=>:baz}}
 

 


© Shin Nakamura/BasicWerk 2014