0
2

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】each_with_objectとinjectの違い

Posted at

##each_with_object
配列やハッシュの要素を使って、新たに配列やハッシュを作成したりする際に簡潔に書くことができる。

  • 引数に渡されたオブジェクトが常にhash変数に入っている。
array = [[:hoge, 1], [:fuga, 2], [:piyo, 3]]

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

# => {:hoge=>1, :fuga=>2, :piyo=>3}

##inject

  • ブロック内で最後に評価された値が入るのでブロック内でもう一度hashを書かないといけない。
array = [[:hoge, 1], [:fuga, 2], [:piyo, 3]]

hash = array.inject({}) do | hash, (key, value) |
  hash[key] = value
  hash
end

#=> {:hoge=>1, :fuga=>2, :piyo=>3}

配列やハッシュの要素から一つのオブジェクトを作る場合に使うほうが向いてる。

array = [2, 3, 4, 5]
array.inject do |result, item|
  result + item
end

#=> 14

##参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?