Iterative processing

What is iterative processing?

If you write the same code 10 times to do the same process 10 times, the code will be difficult and hard to see. It's hard to write, and it's annoying when there are corrections. This process is used when you want to repeat the same process many times to prevent this from happening.

times method

Method to use when you want to repeat the same process multiple times

Numerical value.times do
  #Repeated processing
end

For example

5.times do
  puts "hello"
end

hello
hello
hello
hello
hello

Is output

Block variable

Variables that can only be used inside a method||Different processing can be executed by using the block surrounded by. Variables enclosed in blocks are called block variables.

The block variable of the times method is assigned a numerical value that increases by 1 from 0 for each iteration.

Numerical value.times do |Block variable|   #Each time it is repeated, it increases by 1 from 0
  #Repeated processing
end

For example

5.times do |i| #Define i as a block variable
  puts i + 2
end

2
3
4
5
6

Is output.

each method

It is a method that iterates as many elements as there are elements in the array.

Array.each do |item|
  #processing
end

After each, describe the process you want to repeat between do and end. The block variable contains the elements of the array and is replaced each time it is repeated.

For example

animals = ["cat","dog","rabbit"]   ##Define array

animals.each do |animal|
  puts "animal:#{animal}"
end

animal:cat
animal:dog
animal:rabbit

Is output.

that's all.

Recommended Posts

Iterative processing
[Ruby] Iterative processing
Ruby Iterative Processing
java iterative processing
[Ruby ~ Iterative processing ~] Study memo 4
[Swift] "for-in statement" about iterative processing
Memorandum (other conditional bifurcation, iterative processing)
Date processing
Loop processing
[Beginner] Various iterative processing for Ruby arrays
Omitting iterative processing using render's collection option
[Java ~ Conditional branching / Iterative processing ~] Study memo (3)
Java thread processing
Java string processing
[Java] Multi-thread processing
Stream intermediate processing
Christmas with Processing
[Java] Stream processing
Create versatile processing
Addition of variables in iterative processing in a while statement