Last active
December 15, 2015 04:09
-
-
Save masonforest/5199929 to your computer and use it in GitHub Desktop.
validate USPS tracking numbers in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def valid(tracking_number) | |
chars = tracking_number.chars.to_a | |
expected_check_digit = chars.pop.to_i | |
total = 0 | |
chars.reverse.each_with_index do |digit, index| | |
if index.even? | |
total += digit.to_i * 3 | |
else | |
total += digit.to_i | |
end | |
end | |
check_digit = total % 10 | |
unless check_digit.zero? | |
check_digit = 10 - check_digit | |
end | |
expected_check_digit == check_digit | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment