Scope Scope - 6 months ago 29
Ruby Question

Verifying Length of Integer

Hello Everyone,



I have another Ruby question.
I want to make sure the users input is 5 numbers if its more or less I want it to output Error. I might have the loop wrong I sometimes get it confused.




Do I have to use Integer(gets.chomp)?


Because I have seen that also when getting integers from users.


Here is my code:
#!/usr/bin/env ruby

print "What is your zip code? "
zip_code = gets.chomp
puts zip_code
zip_code_array = zip_code.split

unless zip_code_array.length == 5
puts "Error"
else
puts "Good"
end




Answer

A ZIP code is not an integer. It's a string of five digits.* For example, 00911 is a valid ZIP code (San Juan, Puerto Rico), but it is not an integer in any practical sense.

The correct solution, then, is not to check if the string is an integer of a certain size, but rather if it's a string of five digits.

A regular expression will make short work of this:

print "What is your zip code? "
zip_code = gets.chomp
puts zip_code

if zip_code =~ /^[0-9]{5}$/
  puts "Good"
else
  puts "Error"
end

In case you're not familiar with regular expressions, this one breaks down like so:

/
  ^     # beginning of line
  [0-9] # a digit 0-9
  {5}   # repeated exactly 5 times
  $     # end of line
/x

*Strictly speaking, a ZIP code can be five digits or five digits followed by a dash and four digits (ZIP+4). You'd be wise to accommodate both in your application.