The ** each method ** is a well-known iterative process of ruby, but each is not always the best.
For some patterns, it may be easier to implement by using a different method. This time, I will introduce how to write in a simplified manner for each pattern.
We will use the map
method.
#For 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]
#For 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
We will use the ʻinject (initial value)` method.
#For each
list = (1..5).to_a
sum = 0
list.each do |i|
sum += i
end
p sum # 15
#In case of inject
list = (1..5).to_a
sum = list.inject(0){|i, j| i += j}
p sum # 15
Recommended Posts