LoginSignup
6
4

More than 1 year has passed since last update.

Ruby | ハッシュの各要素に対して いきなりインクリメント ( += ) する

Last updated at Posted at 2016-06-12

解決

Hash.new(0)
Hash.new(10)

などとして、ハッシュキー生成時の初期値を指定しておけば良い。( この場合は 0 が初期値になる )

検証

次のように、key value にたいしていきなりインクリメントして代入ができる。

scores = Hash.new(0)

scores[:Alice] += 1

scores # => {:Alice=>1}
scores = Hash.new(10)
scores[:Bob] += 3

scores # => {:Bob=>13}

応用例

scores = Hash.new(0)

%w(Alice Bob Alice Bob Alice Alice Carol).each do |player|
  scores[player] += 1
end

scores
# => {"Alice"=>4, "Bob"=>2, "Carol"=>1}

問題

Perl だと、変数に対して「いきなりインクリメント」できるので。
Ruby での動作の違いに困っていた。

環境

  • ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

6
4
2

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
4