It seems that there are ** each ** method, ** for ** statement, ** whil, until ** statement, ** times ** method, ** up_to ** method, etc. as types of Ruby iterative processing. I don't understand which process should be used when iterating with paiza's algorithm, so I will summarize the usage and features.
Iterative processing is often used together with arrays (objects that can store multiple data in order (Array class)) and blocks (groups of processing that can be passed as method arguments). In most cases, Ruby iterates using the each method. * In multiple languages, the for, foreach syntax is often used.
Rather than Ruby executing iterative processing as a language function, each method of the array executes iterative processing. The role of each method is to extract from the elements of the array to the end in order. How to handle the extracted one is described in ** block **.
#Example(Processing that adds elements of an array)
numbers = [1, 2, 3, 4]
sum = 0
numbers.each do |n|
sum += n
end
sum #=> 10
The block is the following part of the code above.|n|N isBlock argument(Name is free)The elements of the array passed from the each method are entered.
#Block part
do |n|
sum += n
end
#do ..Instead of end{}use
numbers.each {|n| sum += n}
If you want to simply repeat the process n times without using an array, use the times method of the Integer class.
sum = 0
#Repeat the process 5 times. 0 for n,1,2,3,4 is entered.
5.times {|n| sum += n} or 5.times{sum += 1}
sum #=> 10
If you want to process something while incrementing the number from n to m one by one, use the upto method of the Integer class. Conversely, a downto method that reduces one by one.
#upto method
a = []
10.upto(14) {|n| a << n}
a #=> [10, 11, 12, 13 ,14]
#downto method
a = []
14.doentown(10){|n| a << n}
a #=> [14 ,13 ,12 ,11 ,10]
Syntax for iterative processing. Execute if the conditional expression after while is true. Execute if the conditional expression after until is false.
#while statement
a = []
while a.size < 5
a << 1
end
a #=> [1 ,1 ,1 ,1 ,1]
#until statement
a = [10 ,20 ,30 ,40 ,50 ]
until a.size <= 3 #Keep erasing the last element unless the array a has 3 or less elements.
a.delete(-1)
end
a #=> [10 ,20 ,30]
You can think that the for statement has the same purpose as the each method. However, Ruby seems to be more common to use each method.
numbers = [1 ,2 ,3 ,4]
sum = 0
for n in numbers
sum += n
end
sum #=> 10
#It is also possible to put do and write in one line.
for n in numbers do sum += end
For the time being, it seems good to learn various methods by using other map methods based on each method.
Recommended Posts