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.
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
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.
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