'How to ensure I can't add in integers or any numbers into an array via user input for ruby
I'm trying to create an array that only allows strings to be passed through, no numbers at all. Is there a way to make this possible?
I've tried the below expecting that if an integer got through then it raise an error, however I forgot that the 'gets' method converts everything into a string.
exercise_list = []
loop do
exercise_input = gets.strip.capitalize
if exercise_list.include?(exercise_input) == false && exercise_input.is_a?(Integer) == false
exercise_list << exercise_input
p exercise_input.class
else exercise_input == "quit"
break
end
end
Solution 1:[1]
The value of exercise_input
returned from gets.strip.capitalize
is always a string. Even if "1" is entered, it will just be the string "1". Checking if it .is_a?(Integer)
will always be false.
This is why it is not working, however, making it work depends a little on your requirements. What is an integer?
"1" obviously is, but what about "1 2", "1 a", "1 ", " 1", "1.1", "1,1", "0x1a", "01".
If you want to ask ruby to decide for you, you can try converting it to integer by calling Integer(exercise_input)
and rescue the error if it's not an integer.
Otherwise I suggest you use a regex to check that the string contains what you want expect it to.
Solution 2:[2]
When working with strings, Regex can be really helpful. So, you have an input that is always a string. Eg. "asd12" so you can ask if inside the string there is a number, if there is, you pass to the next input, if not you append it to the array.
In elseif statement you are asking if there is a match with any digit number (/\d/), if there is, you pass to the next iteration.
Here is a website where you can practice regex: www.rubular.com
Here is my code
exercise_list = []
loop do
print ">. "
exercise_input = gets.strip.capitalize
if exercise_input == 'Quit'
break
elsif exercise_input.match?(/\d/)
next
else
exercise_list << exercise_input
end
end
pp exercise_list
I hope you can find it helpful.
PD. print (">. ") its just for visualization
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Siim Liiser |
Solution 2 | Fabio Fiestas |