LoginSignup
0
1

More than 5 years have passed since last update.

RubyのHashを作成するとき、Default valueをempty arrayにするときの注意

Posted at

RubyのHashを作成するとき、Default valueをempty arrayにしたいとき、Hash.new([])とすると、すべての存在しないないkeyに対して同じArray instanceを参照することになります。

そのため、以下のようにHashへElementの追加と、その追加したElementのValueであるArrayにElementの追加を行うと、すべて同じArrayに追加されてしまいます。

hash = Hash.new([])
hash['hoge'] << 'a'
hash['fuga'] << 'b'

hash['hoge']
=> ['a', 'b']
hash['fuga']
=> ['a', 'b']
hash['foo']
=> ['a', 'b']

上記のようにして、別々のElementにするためには、下記のように新しいHashを作る必要があります。

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

参考

0
1
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
0
1