Skip to content

Instantly share code, notes, and snippets.

@masonforest
Last active December 15, 2015 04:09
Show Gist options
  • Save masonforest/5199929 to your computer and use it in GitHub Desktop.
Save masonforest/5199929 to your computer and use it in GitHub Desktop.
validate USPS tracking numbers in Ruby
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