[Beginner] Various iterative processing for Ruby arrays

Execution environment

Since it is a super-basic content, I think that it does not depend on the execution environment, but I will specify it for the time being. OS : macOS Catalina ver10.15.5 Ruby : 2.7.1p83

each

Basic iterative processing. The elements are taken out one by one and processed. Basically, it is surrounded by do ~ end. Pay attention to the scope of variables.

sample.rb


numbers = [1, 2, 4, 5, 6]

total = 0
numbers.each do |num|
  total += num
end
p total # 18 

map

The feature is that it returns an array. The following processing adds 10 to the element and outputs it. For simple processing, you can enter with {} instead of do ~ end.

sample.rb


numbers = [1, 2, 4, 5, 6]

nuadd_num = numbers.map {|num| num + 10}

p add_num
# [11, 12, 14, 15, 16]

select

The values that match the judgment in the process are returned as an array.

sample.rb


numbers = [1, 2, 4, 5, 6]

numbers2 = numbers.select {|num| num % 2 == 0}

p numbers2
# [2, 4, 6]

reject

Values that do not match the judgment in the process are returned as an array. The opposite of select.

sample.rb


numbers = [1, 2, 4, 5, 6]

numbers2 = numbers.reject {|num| num % 2 == 0}

p numbers2
# [1, 5]

inject Folding process. Elements are assigned to num and i, respectively, and processing is performed.

sample.rb


numbers = [1, 2, 4, 5, 6]

numbers2 = numbers.inject {|num, i| num + i}

#1st loop num= 1, i = 2
#Second loop num= 3, i = 4
#3rd loop num= 7, i = 5
#4th loop num= 12, i = 6

p numbers2
# 18

Recommended Posts

[Beginner] Various iterative processing for Ruby arrays
Ruby Iterative Processing
Ruby About various iterative processes
[Ruby ~ Iterative processing ~] Study memo 4
Memorandum (Ruby: Basic grammar: Iterative processing)
Iterative processing
[Ruby] Explanation for beginners of iterative processing with subscripts such as each_with_index!
Ruby Learning # 13 Arrays
About Ruby arrays
java iterative processing
Ruby conditional branch processing
Ruby Joins multiple arrays
Java random, various processing
Ruby Learning # 23 For Loops
Various Ruby string operations
Scraping for beginners (Ruby)
Integer # pow is recommended for iterative squares solving in Ruby