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

図解 inject(reduce)メソッド の挙動 [RUBY技術者認定試験...問題13]

1
Last updated at Posted at 2019-09-24

基本説明

  • injectメソッド:ブロックを使う繰り返し計算を行うのに使います。メソッドの戻り値は最後のブロックの実行結果です。
  • shiftメソッド:配列の最初の要素を削除し、その要素を返す。レシーバ自身を変更するメソッド。配列が空のときはnilを返す。

例題1

以下の出力結果は?

a = [4,3,2,1]
b = a
c = b.shift
puts a.inject { |x, i| x * i } + c

RUBY技術者認定試験 公式ガイド (ITpro BOOKs) 152p 問題13より抜粋

図解

injectは、値を置いておく箱に、全ての要素をひとつずつ、ブロック内部の処理(今回ならx * i)にしたがって順次繰り返しています。

スクリーンショット 2019-09-24 17.19.56.png

変数aにあった配列の最初の要素(4)は、shiftメソッドにより取り除かれました。shiftメソッドはレシーバ自身を変更するメソッドなので。

例題2

inject メソッドの理解に shiftがノイズなので、上記の図解から以下の出力結果を当ててください。

a = [5,4,3,2,1]
puts a.inject { |x, i| x * i }

実行結果は以下でサクッと試せます

Online Ruby Editor and IDE - Fast, Powerful, Free - Repl.it

参考

正解

  • 例題1:10
  • 例題2:120
1
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
1
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?