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 reduce(inject)を使用して計算

Last updated at Posted at 2021-10-03

# 配列の要素をどんどんたたみ込んで計算

配列内の要素を合計する時に、以下のようなコードを書いていた。

def sum(array)
  sum = 0
  array.each do |number|
    sum += number
  end
  return sum 
end 
p sum([5, 10, 20])
# => 35

初期値 = 0 の設定、イテレートの記述でもっさり。
reduceメソッドを使用すると、sumメソッド内のコードを1行に減らすことができる。

def sum(array)
  array.reduce(0) { |sum, num| sum + num }
end
p sum([5, 10, 20])
# => 35

さらに、リファクタリングできる。ただし、.reduce(:+)は.sumとほぼ同じなので以下の2つは同じ結果になる。

def sum(array)
  array.reduce(:+)
end
p sum([5, 10, 20])
# => 35
def sum(array)
  array.sum
end
p sum([5, 10, 20])
# => 35

シンボルを使用してメソッド適用

ブロックの代わりにメソッド名を記述するとメソッドが使える

p ["b", "c", "d"].inject("abbccdddeee", :squeeze)
# => abcdeee

(例)"abbccdddeee"の中から、["b", "c", "d"]をsqueeze(複数文字を一つにまとめる)

https://docs.ruby-lang.org/ja/latest/method/Enumerable/i/inject.html

https://docs.ruby-lang.org/ja/latest/method/String/i/squeeze.html

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?