8
3

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 2015-02-09

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 }

8
3
1

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
8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?