4
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 3 years have passed since last update.

【ruby】map, injectを使ってeachを簡略化する

Posted at

rubyの繰り返し処理として有名なのが、eachメソッドですが、必ずしもeachが最善という訳ではなかったりします。

あるパターンの時は、違うメソッドを使った方が簡略化して、実装できる場合があります。
今回は、パターン別で、簡略化する書き方をご紹介します。

#すでにある配列から、要素を変化させた新たな配列を作成する時

mapメソッドを使っていきます。

###演算子を使っての変化


# eachの場合

list = (1..5).to_a
list_double = []

list.each do |i|
  list_doubule << i * 2
end

p list_double  # [2, 4, 6, 8, 10]

# mapの場合

list = (1..5).to_a

list_double = list.map{ |i| i* 2 }

p list_double  # [2, 4, 6, 8, 10]

###インスタンスメソッドを使っての変化


# eachの場合

array = ["a", "b", "c"]
array_up = []

array.each do |i|
  array_up << i.upcase
end

p array_up  # ["A", "B", "C"]

# mapの場合

array = ["a", "b", "c"]

array_up = array.map(&:upcase)

p array_up  # ["A", "B", "C"]

.map{ |i| i.upcase }をさらに省略させている

#配列の要素(数字)の合計を求める時

inject(初期値)メソッドを使っていきます。


# eachの場合

list = (1..5).to_a
sum = 0

list.each do |i|
  sum += i
end

p sum  # 15

# injectの場合

list = (1..5).to_a

sum = list.inject(0){|i, j| i += j}

p sum  # 15
4
3
2

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
4
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?