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

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.

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

We will use the map method.

Changes using operators


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

Changes using instance methods


#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

When calculating the sum of the elements (numbers) of an array

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

[Ruby] Simplify each using map and inject
Write code using Ruby classes and instances
[Ruby] each nested
[Ruby] Nesting each
Janken program using Ruby and its test (test-unit)
Ruby and Gem
ruby map method
[Each, map ...] I compared the array processing tonight [ruby]
[Ruby] Classes and instances
Symbols and Destructive Ruby
map, compactMap and flatMap
[Ruby] Big Decimal and DECIMAL
Ruby classes and instances
Ruby inheritance and delegation
Ruby variables and methods
hash and each statement
[Ruby] Creating code using the concept of classes and instances
[Ruby on Rails] Infinite scrolling using gem kaminari and jscroll