0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Ruby】空のハッシュに自己代入(+=)したい

Last updated at Posted at 2023-08-03

できなかったこと

{}を定義したhashに自己代入演算子を使ったがエラー

hash = {}
hash[:hoge] += 1 # => undefined method `+' for nil:NilClass (NoMethodError)

解決策

ハッシュにデフォルト値0を設定し解決

hash = Hash.new(0)
hash[:hoge] += 1 # => 1

Hash.new(0)とは?

ハッシュにはキーに対応する値が存在しない時のデフォルト値を設定できる。Hash.new(0)でハッシュを生成した場合、デフォルト値が0になる。
設定がない場合、デフォルト値はnilになる。

hash = {} # => {}
hash.default # => nil

hash = Hash.new(0) # => {}
hash.default # => 0

なぜ自己代入演算子(+=)が使えたのか

自己代入演算子を使わない場合を考えて納得。

hash[:hoge] = hash[:hoge] + 1
# hash[:hoge] = 0 + 1 (hash[:hoge]が0で評価されるためエラーにならない)

hash[:hoge] = hash[:hoge] + 1
# hash[:hoge] = nil + 1 (hash[:hoge]がnilで評価されるためエラーにならない)

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?