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

Enumerable.each_with_object の使い道

More than 5 years have passed since last update.

同じvalueを持つkeyがたくさんあるようなHashを初期化したいときに、
keyのArrayに対してinjectを使うと、
ブロックの最後でhashを返すのを忘れてしまってエラーになることが多いw

value = "xxx"
hash_keys = %[ key1 key2 key3 ]

hash = hash_keys.inject({}) do |_hash, key|
  _hash[key] = value
  _hash # これを忘れがち
end

だけど、each_with_objectを使うと忘れても大丈夫

hash = hash_keys.each_with_object({}) do |key, _hash|
  _hash[key] = value
end

ちなむと、破壊的メソッドで引数のオブジェクトを更新していくだけなので、
immutable なやつとかには使えないし、
文字列操作も普段使わないような破壊的なやつを使わないといけない。

ので、いまのところHashに同じ値を挿入するくらいしか使ったこと無い。

なお、以下のようなコードが一般的だろうがなんとなく好きではない。

hash = {}
hash_keys.each {|key| hash[key] = value }

※ ちなみにeach_with_objectのブロック引数の順番が覚えられないので備忘録ついでに書いたエントリです

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
ユーザーは見つかりませんでした