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

Ruby injectメソッド

More than 5 years have passed since last update.

injectメソッドは、ブロックを使って繰り返し計算を行うのに使います。ブロックに順に「要素1、要素2」、「ブロックの前回の戻り値、要素3」、「ブロックの前回の戻り値、要素4」、...を渡します。メソッドの戻り値はブロックが最後に返した値になります。

引数initで初期値を指定すると、ブロックに「初期値、要素1」、「ブロックの前回の戻り値、要素2」、「ブロックの前回の戻り値、要素3」、...を渡します。

a = [1, 2, 3]
a.inject(0) {|sum, i| sum + i }   # => 6
a.inject(:+)  # => 6

a.inject(:*) # => 6
a.inject(:-) # => -4

(1..10).inject(:+) # => 55

fib = [1, 1]
(0..10).each {|i| fib << fib[i] + fib[i+1]}
p fib # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]
p (0..10).inject([1, 1]) {|fib, i| fib << fib[i] + fib[i+1] }

data = [:A, :B, :A, :C, :E, :A, :D, :B, :B, :C, :E]
h = Hash.new(0)
data.each {|key| h[key] += 1 }
p h # => {:A=>3, :B=>3, :C=>2, :E=>2, :D=>1}

data = [:A, :B, :A, :C, :E, :A, :D, :B, :B, :C, :E]
p data.inject(Hash.new(0)) {|h, key| h[key] += 1; h }

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