0
0

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

【Ruby】injectについて

Posted at

##inject
eachなどのようにブロック内の処理を繰り返し行うメソッド

1~5までの合計を計算する

[1, 2, 3, 4, 5].inject {|sum, num| sum + num } 
#=> 15

↓上のコードと同じことをしている

sum = 0
[1, 2, 3, 4, 5].each {|v| sum += v }
p sum   # => 15

初期値を指定して毎回のループでリセットすることもできる(デフォルトは初期値0なので省略可)

[1, 2, 3, 4, 5].inject(1) {|sum, num| sum + num**2 }
#=> 56

##参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?