I am writing a gem to detect tracking numbers (called tracking_number , natch). He searches for text for valid tracking formats, and then runs these formats by calculating the checksum, as indicated in each relevant service specification, to determine the valid numbers.
The other day, I sent a letter using USPS Certified Mail, received an accompanying tracking number from USPS and submitted it to my gem, and it did not pass the verification. I'm pretty sure I'm doing the calculation correctly, but I have run out of ideas.
The number is confirmed using USS Code 128, as described in section 2.8 (page 15) of the following document: http://www.usps.com/cpim/ftp/pubs/pub109.pdf
The tracking number I received from the mail branch was "7196 9010 7560 0307 7385", and the code that I use to calculate the check digit is:
def valid_checksum?
chars = self.tracking_number.chars.to_a
check_digit = chars.pop
total = 0
chars.reverse.each_with_index do |c, i|
x = c.to_i
x *= 3 if i.even?
total += x
end
check = total % 10
check = 10 - check unless (check.zero?)
return true if check == check_digit.to_i
end
According to my calculations, based on the specification provided, the last digit must be 3 in order to be valid. However, Google’s auto-detection of the tracking number picks up the number of fines as is, so I can only assume that I am doing something wrong.
source
share