Memorandum (Ruby: Basic grammar: Iterative processing)

times method

A method that can iterate a specified number of times

Numerical value.times do
  #Repeated processing
end

Block variable

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

each method

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

Memorandum (Ruby: Basic grammar: Iterative processing)
[Ruby] Iterative processing
Ruby Iterative Processing
Memorandum (Ruby: Basic Grammar: Classes and Instances)
ruby memorandum (basic edition)
Ruby on Rails Basic Memorandum
[Ruby ~ Iterative processing ~] Study memo 4
Review of Ruby basic grammar
Memorandum (Ruby: Basic grammar: Use by naming the process)
Memorandum (other conditional bifurcation, iterative processing)
Iterative processing
Introduction to Ruby basic grammar with yakiniku
[Beginner] Various iterative processing for Ruby arrays
Ruby basic terms
Java basic grammar
Java basic grammar
[Ruby] Method memorandum
Java basic grammar
Java basic grammar
java iterative processing
Ruby conditional branch processing
About Android basic grammar
ruby basic syntax memo
I tried to summarize the basic grammar of Ruby briefly
Basic methods of Ruby hashes
Basic methods of Ruby arrays
RxJava basic processing sequence (old)
Ruby About various iterative processes
[Ruby] List of basic commands
JavaScript overview and basic grammar
Ruby methods and classes (basic)