As a result of trying to do Don't Repeat Yourself (do not repeat the same description), there were cases where the original purpose could not be achieved, so I will leave it as an article.
For example, suppose you want to enter only a specific character string. (In the following case, the input of any one of "0", "1", "2" is judged by the if statement.)
input_number = gets.chomp
sample_number = ["0","1","2"]
if input_number == "0" || input_number == "1" || input_number == "2"
puts "Input is 0,1,It is one of 2."
else
puts "0,1,Characters other than 2 have been entered!"
end
Logical operator||It seems that the (or) part is long ... I try to make it simple by trial and error.
case1 between?Method
input_number = gets.chomp
sample_number = ["0","1","2"]
#The entered character string is"0"From"2"Returns the truth as to whether or not it is between.
t_or_f = input_number.between?("0", "2")
if t_or_f == true
puts "The entered character string is 0,1,Is one of 2"
else
puts "Other characters are included!"
end
The number of variable definitions has increased by one, but if you want to accept more character strings, you need to add or modify less than logical operators. It turns out that the refactoring is over and that another problem arises. If it contains an unrelated character string such as an alphabet, it will be false, but an input such as "0120" or "1.9" will be returned as true. What about next?
any?Methods and include?Method
input_number = gets.chomp
sample_number = ["0","1","2"]
#any?Method: Returns true if any one of the conditions is met, false if none of the conditions are met
#block{}Processing in ... sample_numberの配列内の要素をblock引数nに代入。
#input_Judges whether the block argument n is included (included) in number, and returns true or false repeatedly (in this case, 3 times).
t_or_f = sample_number.any? {|n| input_number.include?(n)}
if t_or_f == true
puts "The entered character string is 0,1,Is one of 2"
else
puts "Other characters are included!"
end
In this case, if the input character string contains either 0, 1, or 2, it will always return true. (Example: 1234 => true, abc0120 => true)
After all, logical operators||Strict input is the most accurate.
The extended Ruby in Rails, rather than the Ruby original, has a __in? Method __. In this case, only 0,1,2 are accepted, 01 etc. are not passed.
in?Method
input_number = gets.chomp
if input_number.in?(["0", "1", "2"])
puts "The entered character string is 0,1,Is one of 2"
else
puts "Other characters are included!"
end
Recommended Posts