[Each, map ...] I compared the array processing tonight [ruby]

There are many methods for manipulating the elements of ruby's array. After all, I tried to compare which one behaves and which one is the most efficient.

Array operation quick reference table

Method Return value behavior
each Array of receivers Iterate over the elements of the array one by one in the block
each_slice nil Iterate over multiple units of array elements in a block
each_with_index Array of receivers Iterate over array elements and index numbers within a block
map Changed array Change elements as they are in an array
select Changed array Keep the array and narrow down the elements for which the conditional expression is true
reject Changed array Keep the array and narrow down to the elements whose conditional expression is false
find element elementの中で、最初にヒットしたelementを取り出す

Iterative processing

each Loop the element in the singular


array = ["Apple", "Orange", "watermelon", "melon"]

array.each do |obj|
  p obj
end

Return value


Apple
Orange
watermelon
melon
=> ["Apple", "Orange", "watermelon", "melon"]

each_slice Loop multiple elements


array.each_slice(2) do |a|
  p a
  p a
end

Return value


["Apple", "Orange"]
["watermelon", "melon"]
=> nil

each_with_index You can retrieve the index along with the element


array.each_with_index do |obj,index|
  p obj
  p index
end

Return value


"Apple"
0
"Orange"
1
"watermelon"
2
"melon"
3
=> ["Apple", "Orange", "watermelon", "melon"]

Directly change the contents of the element

map Tweak the elements and return as an array


array = [1, 2, 3, 4, 5]

array_new = array.map{ |i| i*2 }

Return value


[2, 4, 6, 8, 10]

select Returns an array with elements whose conditional expression return value is true


array = [1, 2, 3, 4, 5]

array_new = array.select{ |i| i > 3 }

Return value


[4, 5]

reject Returns an array with an element whose conditional expression return value is false


array = [1, 2, 3, 4, 5]

array_new = array.reject{ |i| i % 2 == 0 }

Return value


[1, 3, 5]

find Find and retrieve the first element that is true in the conditional expression


array = [1, 2, 3, 4, 5]

array_new = array.find{ |i| i > 3 }

Return value


4

Recommended Posts

[Each, map ...] I compared the array processing tonight [ruby]
Array / list / map
[Each, map ...] I compared the array processing tonight [ruby]
[Ruby] Tonight, I tried to summarize the loop processing [times, break ...]
Iterative processing of Ruby using each method (find the sum from 1 to 10)
[Ruby] Simplify each using map and inject
I investigated the internal processing of Retrofit
I compared the characteristics of Java and .NET
I summarized the naming conventions for each Rails
I checked the number of taxis with Ruby
I want to get the value in Ruby