LoginSignup
6
7

More than 5 years have passed since last update.

Ruby で Perl 的な何段にも深い Hash をクールに実現する

Posted at

Ruby を使い始めてから、それまで使っていた Perl と比較して、この機能があったらとずっと思っていたのが、深い連想配列(Hash) が簡単につくれる機能でした。

Perl では次のような物が動作します。

recursive_hash.pl
my $h = {};
$h->{1}{2}{3}{4}{5} = 1;

これを Ruby でクールに実現するには、以下のように記述します。

recursive_hash.rb
rh_proc = lambda { Hash.new { |h, k| h[k] = rh_proc.call } }
h = rh_proc.call
h[1][2][3][4][5] = 1

上記は以下を参考にさせていただきました。
Rubyで再帰可能なhash(recursive hash)を作る

オリジナルはメソッドを別に定義して、名前空間を汚していたので、
lambda 式を使うようにしました。

6
7
0

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
  3. You can use dark theme
What you can do with signing up
6
7