0
1

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 5 years have passed since last update.

Rubyのinjectメソッドについての自分用解説

Last updated at Posted at 2018-09-20

Rubyにて、配列で使うinjectメソッドがなかなか理解できなかったので、自分なりに整理してメモとして残します。
なにぶん初心者ですので、理解が誤っている場合等はご指摘いただければ幸いです。

###通常の記法

test.rb
array = [1, 2, 3, 4].inject(0) {|result, item| result + item }
 # => 10

このように記述したとき、次のような順番で処理が行われる。

  • injectの引数「0」を初期値としてresultに代入
  • arrayの要素「1」をitemに代入
  • result + itemの結果をresultに代入
  • arrayの要素「2」をitemに代入

...以降繰り返し

###引数「0」を省略した記法

test.rb
array = [1, 2, 3, 4].inject {|result, item| result + item }
 # => 10
  • arrayの要素「1」を初期値としてresultに代入
  • arrayの要素「2」をitemに代入
  • result + itemの結果をresultに代入
  • arrayの要素「3」をitemに代入

...以降繰り返し

引数が省略された場合は、配列の1番目の要素が初期値となり、2番目の要素からループが始まる。

###さらに省略した記法

test.rb
array = [1, 2, 3, 4].inject(:+)
 # => 10

省略されすぎて何がなんだかわかりにくいが、:+のように演算子を渡すと、ひとつ上の記法と同じ意味になる。
inject(:+)では配列の要素の和を返し、inject(:*)では配列の要素の積を返すことができる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?