LoginSignup
4

More than 5 years have passed since last update.

Rubyで再帰的にアクセス可能なHashを定義する

Last updated at Posted at 2017-03-01

小ネタ

h = Hash.new {|h, k| h[k] = Hash.new {|h, k| h[k] = {} } }

p h[:a]           #=> {}
p h[:a][:b]       #=> {}
p h[:a][:b][:c]   #=> nil
p h               #=> {:a=>{:b=>{}}}

rh = Hash.new {|h, k| h[k] = Hash.new(&h.default_proc) }

p rh[:a]          #=> {}
p rh[:a][:b]      #=> {}
p rh[:a][:b][:c]  #=> {}
p rh              #=> {:a=>{:b=>{:c=>{}}}}

:muscle:

Hash#default_proc を利用して再帰的にHash.newを行うようにすることで、どこにアクセスしても {} を返してくれるHashを定義することが出来ます。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
4