I am trying to create a method that asks for the user to create a pin number, like a bank account pin. It can only be 4 numbers in length, and every character entered must be numbers. I have found when I use this code:
puts "Please give us a 4 digit pin number for your account:"
@response = gets.chomp
unless @response.to_i.is_a?(Integer) && @response.to_str.length == 4
puts "Your response must be 4 numbers in length."
create_pin
else
@pin = @response.to_i
puts "Your pin has been set."
end
It does not work as I would prefer, because the .to_i method will gladly convert '2134a' to 2134. As well, if there is no Integer in the string, it records the value as 0, which is not false as I need it to be.
Test if a string is basically an integer in quotes using Ruby?
I found a really helpful post, but it seems to get quite complicated in the thread do to regexp. This post was also shut down because the creator was not specific enough:
Check if string contains only positive numbers in Ruby
So I'll try be clear, I am trying to limit the user input so they can only type numbers 0 through 9. Math equations like 10^3 need to be fail, as well as negative numbers like -1234, and I'm trying to limit them to four digits the way any pin would be limited. So far, I'm completely stumped and haven't seen a way to do it that doesn't contain a whole bunch of regexp.
Perhaps I could check if the string contains a list of unacceptable characters.
Thanks ahead.
Edited for better phrasing and to correct an error I wrote in the second paragraph.