[RUBY] Order of processing in the program

The study period is now in the 11th week. Here's a look back at what I've learned and what I often make mistakes.

This time is "processing order". Although it is a basic and rudimentary content in the basics, there are many cases where an error occurred due to the wrong order of description, so I hope it will be helpful for those who are just starting to learn. Also, since the language currently being learned is "Ruby", the content will also be that of "Ruby".

The version of ruby you are using is as follows.

ruby 2.6.5

About the order of processing

First of all, the order of program processing in the source is basically ** "line by line from top to bottom" *. This doesn't change when you create an app using complicated description or Ruby on Rails. ( When calling a method, conditional branching, or repeating processing, the line may jump from bottom to top, but it will be easier to understand if you are aware of the basic processing order.) Expressed in a simple program,

puts "1st line"
puts "2nd line"
puts "3rd line"

If you write, when you execute it on the console

1st line
2nd line
3rd line

It will be. With this description, the output result of the program puts "3rd line" will not come to the 1st line. It would be hard if there was. If conditional branching (if, while, etc.) or repetitive processing (times, each, etc.) overlaps with this, the order of processing tends to be sloppy. (Maybe I'm the only one ...)

Take, for example, the famous ** "FizzBuzz Problem" **.


FizzBuzz problem
 1~Create a program that outputs the number 100.
When it is a multiple of 3, it is displayed as "Fizz", and when it is a multiple of 5, it is displayed as "Buzz".
Make a program to display.
However, when it is a multiple of 15, display "FizzBuzz".

An example of this answer is

#Correct code
def fizz_buzz
  num = 0
  while num <= 99
    num += 1
    if num % 15 == 0 
    puts "FizzBuzz"
    elsif num % 3 == 0
    puts "Fizz"
    elsif num % 5 == 0
    puts "Buzz"
    else
    puts num
    end
  end
end

puts fizz_buzz

The output result is as follows

スクリーンショット 2020-09-28 10.56.51.png

Let's change the order of the conditional expressions in this program as follows.

#Wrong code

def fizz_buzz
  num = 0
  while num <= 99
    num += 1
    if num % 3 == 0  # num % 15 ==Change from the conditional expression of 0
    puts "Fizz"
    elsif num % 5 == 0
    puts "Buzz"
    elsif num % 15 == 0 #num % 3 ==Change from the conditional expression of 0
    puts "FizzBuzz"
    else
    puts num
    end
  end
end

puts fizz_buzz

Here is the output result when described as above.

スクリーンショット 2020-09-28 11.07.44.png

When it is a multiple of 15, "FizzBuzz" is not displayed but "Fizz" is displayed. The reason for this is "I don't understand the order of program processing."

Given the order of processing the wrong code above, For example, if num == 3,

#Wrong code
    if num % 3 == 0  #This formula applies
    puts "Fizz"

=> "Fizz"

When num == 5

#Wrong code
    if num % 3 == 0  # num ==5 is not divisible by 3, so do the following
    puts "Fizz"
    elsif num % 5 == 0 # num ==5 is divisible by 5, so do this
    puts "Buzz"

=> "Buzz"

If the problem num == 15

#Wrong code
    if num % 3 == 0  # num ==15 is divisible by 3, so do this!
    puts "Fizz"
    elsif num % 5 == 0 # num ==15 was processed and no longer works.
    puts "Buzz"
    elsif num % 15 == 0 # num ==15 was processed and no longer works.
    puts "FizzBuzz"
    end

=> "Fizz"

It will be processed like this. So be careful about the order in which you write the program.


if num % 15 == 0 #First, it is determined whether num is divisible by 15.
    puts "FizzBuzz" #If the conditional expression applies"FizzBuzz"If the display does not apply, go to the next

  elsif num % 3 == 0 #Next, it is not divisible by 15, but it is judged whether it is divisible by 3.
    puts "Fizz"      #If the conditional expression applies"Fizz"Is displayed.
                     #If this also does not apply, go to the next

  elsif num % 5 == 0 #It is not divisible by 3 or 15, but it is judged whether it is divisible by 5.
    puts "Buzz"      #If the conditional expression applies"Buzz"Is displayed.
                     #If this also does not apply, go to the next
  else
 
   puts num         #If all the previous conditions are not met
end                 #Display num as it is

that's all. Although it is a basic thing, from my experience so far, there was a situation where I was in trouble because I did not have a solid grasp of these basics, so I would appreciate it if you could refer to it if you face a similar situation.

Recommended Posts

Order of processing in the program
[Order method] Set the order of data in Rails
About the problem of deadlock in parallel processing in gem'sprockets' 4.0
Image processing: The basic structure of the image read by the program
Explanation of the order of rails routes
Implementation of asynchronous processing in Tomcat
A program that counts the number of words in a List
[Java] Get the dates of the past Monday and Sunday in order
Android --Is the order of serial processing and parallel processing of AsyncTask guaranteed? ??
Spring validation was important in the order of Form and BindingResult
Get the result of POST in Java
The identity of params [: id] in rails
Implementation of multi-tenant asynchronous processing in Tomcat
[Swift] Termination of the program by assertion
I investigated the internal processing of Retrofit
The story of AppClip support in Anyca
The story of writing Java in Emacs
Write the movement of Rakefile in the runbook
Sample program that returns the hash value of a file in Java
[No.004] Corrected the order list screen of the orderer
The story of low-level string comparison in Java
[Java] Handling of JavaBeans in the method chain
The story of making ordinary Othello in Java
About the description order of Java system properties
The order of Java method modifiers is fixed
The story of learning Java in the first programming
Measure the size of a folder in Java
Feel the passage of time even in Java
Order of modifiers used in Swift (see SwiftLint)
Import files of the same hierarchy in Java
[Swift] Termination of the program by the fatalError function
[Rails] Ranking and pagination in order of likes
Creating a sample program using the problem of a database specialist in DDD Improvement 2
[Swift] How to change the order of Bar Items in Tab Bar Controller [Beginner]
Creating a sample program using the problem of a database specialist in DDD Improvement 1
Get the URL of the HTTP redirect destination in Java
Specify the encoding of static resources in Spring Boot
Count the number of occurrences of a string in Ruby
The world of clara-rules (2)
In Time.strptime,% j (total date of the year) is
Simple plugin mechanism in Spring, also consider the order
Prepare the execution environment of Tomcat in IntelliJ Community
Access the war file in the root directory of Tomcat
Return the execution result of Service class in ServiceResponse class
Implementation of asynchronous processing for single tenant in Tomcat
[Ruby] The role of subscripts in learning elements in arrays
Get the name of the test case in the JUnit test class
Review the multilingual support (i18n) of the ios app in 3 minutes
Understand the characteristics of Scala in 5 minutes (Introduction to Scala)
Judgment of the calendar
The story of an Illegal State Exception in Jetty.
The world of clara-rules (4)
Examine the boundaries of the "32GB memory wall" in Elasticsearch
The world of clara-rules (3)
Addition of variables in iterative processing in a while statement
[Java] Get the file in the jar regardless of the environment
The objects in the List were references, right? Confirmation of
Personal summary of the guys often used in JUnit 4
Use MouseListener in Processing
The world of clara-rules (5)
The idea of quicksort