[Ruby] Implement error handling / iteration processing using while method

Overview

While studying ruby, I thought "I want to create a portfolio only with Ruby!", So I created a portfolio with ruby. If you can get to know this description early! There were many things I thought. So, I wrote this article, hoping that it would be helpful for those who have the same feeling of ** wanting to create a program using Ruby **.

Content of this article

What is a while method?

** A method that loops until the conditions are met ** When combined with an if statement, it can be used as follows

Basic


while true
if condition
true processing
    break
  else
Handling of false
  end
end

You can also handle errors as ** "a method that allows you to request as many times as you want until the requested value is entered" **.

Scene to use

** When you want to accept only the correct value at the time of conditional bifurcation! !! ** **

Do you put foreign money into Japanese vending machines to buy juice? I don't do that, and it's very likely that it won't come out if you force it in. Or it may break down.

It's the same program, ** If you cannot get the correct value (coins), the program (vending machine) will not work. ** **

Therefore, it is necessary to have a program that can tell ** "Please insert Japanese coins" ** when foreign coins are thrown into a vending machine. Let's do that with the ** while method **.

Example sentence

This time, we will create a program that supports error handling by combining ** "while method" ** and ** "if statement" **.

** This program ** --Require input of amount --If you enter a "number" of "100 or more", "true" is output. --In other cases, "false" is output.

Ordinary if statement

main.rb


    #① Store the entered money in a variable called money
    print "Please put in the money."
    money = gets.chomp.to_i

    #② Conditional bifurcation with the numerical value included in money
    if money >= 100 
       
       #=>For the requested number
       puts "I received more than 100 yen"
       #End

    else
       
       #=>For unrequested values
       puts "It's less than 100 yen, so it's not worth it. Please enter the money again."
       #End

    end

When you run the program ... スクリーンショット 2020-12-13 17.59.56.png

The if statement branches "if it matches" and "if it doesn't match", ** If you branch, it will end **, so you will need to start the program (ruby main.rb) each time.

if statement with while true

So what happens if you include a while method? (Changes are represented by "+")

main.rb



+  while true

    #① Store the entered money in a variable called money
    print "Please put in the money."
    money = gets.chomp.to_i

    #② Conditional bifurcation with the numerical value included in money
    if money >= 100 
       
       #=>For the requested number
       puts "I received more than 100 yen"
+      break
       #End

    else
       
       #=>For unrequested values
       puts "It's less than 100 yen, so it's not worth it. Please enter the money again."
+      #Do not finish, return to the beginning

    end


+ end


When I run the program again ...

スクリーンショット 2020-12-13 18.04.56.png

What do you mean? Just put the while method ** Wouldn't the program ask you many times! ! ** Even if you look at the execution result, you can see that the process is looping because "ruby main.rb" is executed only once. This allows you to repeat until you enter the value requested by the program. It is possible to handle error handling.

However, if you do not insert ** "break" **, it will loop forever, so be sure to insert it firmly!

Iterative processing

In addition to error handling during conditional bifurcation, you can also use the following!

Repeat with a limited number of times

I reproduced "Penalty shootout of soccer". At that time, I used it to implement *** "Processing that repeats only 5 times" ***! (Simplified this time)

** This program ** --Implement the same process repeatedly --Implement so that the count increases by 1 each time it is performed. --If you exceed the limit (<5 this time), it will end.

main.rb


#Initial value of the number of times
kick_count = 0 

while kick_count < 5
  kick_count += 1   #=>+1 count(kick_count = kick_count +Abbreviation for 1)
  puts "output"       #=>Repeat this
end

Output result スクリーンショット 2020-12-13 19.52.26.png

Now you have a program that executes the same process 5 times. This still works, but there is actually one part I want to fix.

It is **, storing the parts that may change in the future in variables or constants instead of numbers **. In this case, it will be "5" while count <5.

main.rb


  count = 0
+ GAME_NUM = 5  #=>Store 5 times in a constant

# -  while count < 5
+  while count < GAME_NUM
    count += 1
    puts "output"
  end

By storing in a constant as described above, even if the number of games changes, You can easily change it by changing the value of GAME_NUM. This time there is only one place to use GAME_NUM, If you have written many places, it is convenient because you can change all of them.

This time, we talked about how to implement iterative processing and error processing using the ** while method **.

Summary

Thank you for your help when dealing with error handling and iterative processing. I would like to write other ruby ​​articles, so I would appreciate it if you could read them.

Recommended Posts

[Ruby] Implement error handling / iteration processing using while method
Implement common processing using method swizzling on iOS
Implement declarative retry processing using Spring Retry
[Ruby] Search problem using index method
Iterative processing of Ruby using each method (find the sum from 1 to 10)
[Ruby] Obtaining even values ​​using the even? Method
Tips for gRPC error handling in Ruby
Get the error message using the any? method
Error handling when Gradle dependency is using SLF4J
Rails error undefined method ʻimage_name'for nil: NilClass handling