A method that can iterate a specified number of times
Numerical value.times do
#Repeated processing
end
Variables that can only be used in methods,||Surround with The block variable of the times method is assigned a numerical value that increases by 1 from 0 each time the iterative process is executed.
Numerical value.times do |Block variable|
#Repeated processing (block variables starting from 0 can be used)
end
Example:
10.times do |i|
puts i + 1
end
#Processing to add 1 to the block variable starting from 0
A method that can iterate over each array as many times as there are elements in the array By placing a block, the block variable will contain the elements of the array
Array.each do |item|
#processing
end
#each followed by do~Describe the process you want to repeat between end
Example:
colors = ["Grime", "Blue", "yellow"]
colors.each do |color|
puts "color: #{color}"
end
output:
% ruby loop.rb
color:Grime
color:Blue
color:yellow
Recommended Posts