Help us understand the problem. What is going on with this article?

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

解決

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]

参考

YumaInaura
Ruby on Rails 業務経験 約5年 / Perl PHP Python Golang Linux Apache MySQL BigQuery Jenkins ansible AWS など / いなうらゆうま / YumaInaura / 稲浦悠馬
http://twitter.com/yumainaura
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした