[Ruby] Classification and usage of loops in Ruby

Why write

I implemented while and redo in business and looped until the conditions were met, and I ran the job in the production environment, so the output to write an appropriate loop. (Even with paiza, it was all about while, ...)

At the time of code review, I was often asked to rewrite with one liner, so I will write one liner notation as far as I can understand.

Loop types and uses

for (I don't think it's used much in Ruby ...) The for statement is used when you want to repeat the processing for the range of the specified range object or get the elements of the array in order.

ruby.rb


for i in 1..3 do
  p "#{i}Second loop"
end

#=>"1st loop"
#=>"Second loop"
#=>"3rd loop"

It is possible to get the elements of the array in order, but I don't think there are many people who write for for, and there is no merit, so I will omit it.

each It is a familiar each in Ruby.

Each method is a method that can be used in arrays, range objects, Hash, and Enumerator, and you can get the elements contained in the object in order.

ruby.rb


#Array
[1,2,3].each do |i|
  p "#{i}Second loop"
end

#Array one liner
[1,2,3].each {|i| p "#{i}Second loop"}

#Range object
(1..3).each do |i|
  p "#{i}Second loop"
end

#Range Object One Liner
(1..3).each {|i| p "#{i}Second loop"}

#=>"1st loop"
#=>"Second loop"
#=>"3rd loop"

"Each" is mainly used rather than "for".

while Next is while (I did it while) While loops while the specified condition is true.

While the for statement and each method iterate over the specified elements, the while statement iterates until the conditional expression becomes false.

ruby.rb


i = 1
while i <= 3 do #do is optional and works without writing
  p "#{i}Second loop"
  i += 1
end

#=>"1st loop"
#=>"Second loop"
#=>"3rd loop"

I think there is more risk than each or times that will be introduced in the future. There is no clear and reliable upper limit, and you set the conditions yourself, so use it systematically ...

If you understand and use it, it will be flexible and insanely easy to use.

until Think of it as the exact opposite of while. It may not be very useful, but for the time being.

ruby.rb


i = 1
until i > 3 do #do is optional and works without writing
  p "#{i}Second loop"
  i += 1
end

#=>"1st loop"
#=>"Second loop"
#=>"3rd loop"

The condition is reversed from the previous one, and it will rotate unless the predefined i exceeds 3. I don't recommend it because it's difficult to understand, but if you don't use the numerical value as a condition, it seems to be useful.

loop This will not come out unless you end it with break. You can set flexible conditions, but I think this is also a fairly risky loop.

ruby.ruby.rb


i = 1
loop{
  p "#{i}Second loop"
  i += 1
  break if i == 4
}

#=>"1st loop"
#=>"Second loop"
#=>"3rd loop"

When the defined variable "i" becomes equal to 4, it breaks.

times I've been using it a lot lately, but I really like it (laughs) I think it is best to turn it the specified number of times.

ruby.rb


#When using a loop degree value
3.times do |i|
  p i
end

#One liner
3.times {|i| p i}

#=>"0"
#=>"1"
#=>"2"

#When not using the loop degree value
3.times do
  p "It's a loop, it turns 3 times"
end

#One liner
3.times {p "It's a loop, it turns 3 times"}

#=>"It's a loop, it turns 3 times"
#=>"It's a loop, it turns 3 times"
#=>"It's a loop, it turns 3 times"

It is recommended because it is the most explicit and intuitive when turning the specified number of times.

upto downto This is also often used when you want a numerical value while turning in a loop. I personally like it.

upto is a loop until the specified number is reached, in which the variable is incremented by 1, and downto is the opposite of upto, which is a loop until the specified number is reached, during which the variable is decremented by 1.

ruby.rb


#upto
1.upto(3) do |i|
  p "#{i}Second loop"
end

#upto one liner
1.upto(3) {|i| p "#{i}Second loop"}

#=>"1st loop"
#=>"Second loop"
#=>"3rd loop"

#downto
3.downto(1) do |i|
  p i
end

#downto one liner
3.downto(1) {|i| p i}

#=>3
#=>2
#=>2

map map iterates through the blocks as many times as there are elements in the array and returns the resulting array. map! does not affect the original value, while map! rewrites the original value. Also, Ruby has a collect method, which is another name for the map method.

It's convenient to be able to process in an array and receive the result as an array.

ruby.rb


arr = [1, 2, 3]
arr_new = arr.map { |x| x * 2 }
p arr_new

#=>[2, 4, 6]

Difference from each

As I get used to Ruby, I think I tend to write everything in each (I also try not to do that). However, there are surprisingly many patterns that can be applied neatly when using map rather than each.

each.rb


#each
int_list = (1..3).to_a

int_to_double = []
int_list.each do |i|
  int_to_double << i * 2
end

p int_to_double

#=>[2, 4, 6]

I'm defining an array just to generate a new list. This is by using map ...

map.rb


#map
int_list = (1..3)

int_to_double = int_list.map do |i| 
  i * 2
end

p int_to_double

#One liner
int_list = (1..3)

int_to_double = int_list.map {|i| i * 2}

p int_to_double

#=>[2, 4, 6]

You can write so neatly.

Finally

In addition, there are still many repetitive syntaxes and methods in Ruby, so I will add them again after checking the timing.

If you want to process an array and generate a new array, use map. If you want to take out the contents of the array one by one and perform conditional branching etc., use each When you want to set flexible conditions and run a loop, use while (use it systematically) If you know the number of loops in advance, set times If you want to get a value that increases or decreases by 1 while turning the loop, use upto, downto.

I use it properly like this.

There are many things you want to do while turning the loop, so the most intuitive way is to select and implement the smart loop.

Recommended Posts

[Ruby] Classification and usage of loops in Ruby
Summary of hashes and symbols in Ruby
Judgment of fractions in Ruby
Handling of date and time in Ruby. Use Date and Time properly.
Handling of line beginning and line ending in regular expressions in Ruby
Basics of sending Gmail in Ruby
Implementation of ls command in Ruby
[Ruby] then keyword and case in
Write keys and values in Ruby
[Rails] Differences and usage of each_with_index and each.with_index
Acquisition of article information in ruby ​​scraping
Directory information of DEFAULT_CERT_FILE in Mac ruby 2.0.0
Make bubble sort and selection sort in Ruby
Explanation of Ruby Time and Date objects
Basic usage of enums and code examples
Difference between "|| =" and "instance_variable_defined?" In Ruby memoization
Comparison of JavaScript objects and Ruby classes
Introduction and usage explanation of Font Awesome
Discrimination of Enums in Java 7 and above
[Ruby basics] About the role of true and break in the while statement
[Ruby] Behavior of evaluation of conditional expression in while
[Ruby] Arguments with keywords and default values of arguments
Recommendation of Service class in Ruby on Rails
Introduction and basic usage of Simple Calendar gem
[Understanding] Differences between hashes and arrays in Ruby
Class in Ruby
Put CSV files containing "'" and "" "in MySQL in Ruby 2.3
[Ruby] "Reference to object" and "Contents of variable"
Basics of Ruby
Ruby on Rails ~ Basics of MVC and Router ~
Learn the rudimentary mechanism and usage of Gradle 4.4
[Java] Classification memo of compilation error and run-time error
Enumerate subsets of arrays given in Ruby (+ α)
Ruby and Gem
Toward understanding of map and flatmap in Stream (1)
Just put `clang 12.0.0` in macOS` Catalina` and put `ruby 3.0.0`
Create a native extension of Ruby in Rust
[Rails] Ranking and pagination in order of likes
Find the greatest common divisor and least common multiple of any number of integers in Ruby
Summary of frequently used commands in Rails and Docker
Count the number of occurrences of a string in Ruby
Use of Japanese fonts and external characters in JasperReport
Usage of th: include, th: replace, th: insert, th: fragment in Thymeleaf
[Ruby] The role of subscripts in learning elements in arrays
Differences between Ruby syntax error statements in Ruby and binary
About the difference between classes and instances in Ruby
In fact, Ruby distinguishes between line breaks and whitespace.
LinkedHashMap referenced in insertion order and its usage example
Usability of date and time classes in each language
[Ruby] Difficulty in refactoring logical operators (accuracy and readability)
How to handle TSV files and CSV files in Ruby
[Technical memo] About the advantages and disadvantages of Ruby
Use of Abstract Class and Interface properly in Java
[Ruby] Class nesting, inheritance, and the basics of self
Get the URL of the HTTP redirect destination in Ruby
Symbols and Destructive Ruby
About eval in Ruby
[Ruby] Big Decimal and DECIMAL
Ruby Learning # 21 While Loops
Minimal usage of Mockito
definition of ruby method