I would like to create a function to enter a name. However, if there is a period or space other than the name, an error will be displayed.
I would like to think about it using the include? method. The include? method is a method that determines whether the specified element is included in an array or character string. reference: Ruby 3.0.0 Reference Manual, include?
Example)
array = ["foo", "bar"]
puts array.include?("bar")
# => true
puts array.include?("hoge")
# => false
I want to create a method to check if the name can be registered properly, so the method name is check_name.
Output example is
Please enter your name(Example)SuzukiIchiro
SuzukiIchiro(The name you entered)
→ Registration is complete
Suzuki.Ichiro(The name you entered)
→!error!Symbols cannot be registered
Suzuki Ichiro(The name you entered)
→!error!Space cannot be registered
I will make it output like this.
First, we will use a guide for you to enter and a method for entering characters.
puts "Please enter your name(Example)SuzukiIchiro"
str = gets
By using the gets method and setting str = gets, the name entered in the terminal will be assigned to str.
Next, create a check_name method and write a description that calls it.
def check_name(str)
end
puts "Please enter your name(Example)SuzukiIchiro"
str_1 = gets
check_name(str_1)
The actual argument (str_1) of check_name (str_1) is set to the name entered in the gets method. When the check_name method is called, the value set in the simultaneous actual argument is passed to the formal argument (str).
Finally, we will describe the processing in the check_name method. We will describe by combining conditional branching and include? Method.
def check_name(str)
if str.include?(".")
puts "!error!Symbols cannot be registered"
elsif str.include?(" ")
puts "!error!Space cannot be registered"
else
puts "Registration has been completed"
end
end
puts "Please enter your name(Example)SuzukiIchiro"
str_1 = gets
check_name(str_1)
Since the if statement ends processing when the condition is met, the conditional expression that indicates whether there is a period or space first is described first.
You have now created a conditional name entry function.
Recommended Posts