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メソッドとは

ブロックを使用して繰り返し処理を行うメソッド
具体的には以下のように記述する

配列.inject {|初期値, 要素| 処理内容 }

使用例

  • injectメソッドの引数にsumの初期値を入れる

サンプルコード

[1,2,3].inject (0){ |sum, array_num| 
   p "array_num=#{array_num}"
   p sum+=array_num
}

実行結果

"array_num=1"
1
"array_num=2"
3
"array_num=3"
6
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?