[Ruby] [Ruby] Simplify each using map and inject

1 minute read

The each method is famous as iterative processing of ruby, but each is not necessarily the best.

For some patterns, using a different method may be easier and easier to implement. This time, I will introduce the simplified writing method for each pattern.

When creating a new array with elements changed from an existing array

We will use the map method.

Change using ### operator


# 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]

For #map

list = (1..5).to_a

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

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

Changes using instance methods


# each

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

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

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

For #map

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

array_up = array.map(&:upcase)

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

.map{ |i| i.upcase } is further omitted

When calculating the sum of array elements (numbers)

We will use the inject (initial value) method.


# each

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

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

p sum # 15

For # inject

list = (1..5).to_a

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

p sum # 15