Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
4
Help us understand the problem. What is going on with this article?
@YumaInaura

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

More than 1 year has passed since last update.

解決

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]

参考

4
Help us understand the problem. What is going on with this article?
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
YumaInaura
Ruby on Rails 業務経験 約5年 / Perl PHP Python Golang Linux Apache MySQL BigQuery Jenkins ansible AWS など / いなうらゆうま / YumaInaura / 稲浦悠馬

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
4
Help us understand the problem. What is going on with this article?