[Ruby] [Beginner] Various iterative processing for Ruby arrays

1 minute read

Execution environment

It’s super basic content, so I don’t think it depends on the execution environment, but I’ll specify it for now. OS: macOS Catalina ver10.15.5 Ruby: 2.7.1p83

each

Basic iterative process. The elements are taken out one by one and processed. Basically it is surrounded by do ~ end. Note the variable scope.

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 process adds 10 to the element and outputs it. If it is a simple process, you can enter {} 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

The values that do not match the judgment in processing 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

Convolution processing. The elements are assigned to num and i, 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