-
-
Save elixirdada/46ae2fced574d50bc8ee734f1b9c9711 to your computer and use it in GitHub Desktop.
This Ruby file includes Ruby functions that Luhn algorithm is implemented. checkLuhn1 returns value if current barcode(including check digit) validates. checkLuhn2 returns value that current barcode join its checkdigit as suffix.
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 sumLuhn (barcode, nParity) | |
checksum = 0 | |
for i in 0..barcode.length - 1 | |
nDigit = barcode[i].to_i | |
if nParity == i % 2 | |
nDigit = nDigit * 2 | |
end | |
checksum = checksum + nDigit / 10 + nDigit % 10 | |
end | |
return checksum % 10 | |
end | |
#return turn if current barcode( including checkdigit ) validates, false if not. | |
def checkLuhn1(barcode) | |
nParity = barcode.length % 2 | |
return sumLuhn(barcode, nParity) == 0 | |
end | |
#return string if current barcode joined checkdigit as suffix. | |
def checkLuhn2(barcode) | |
nParity = 1 - barcode.length % 2 | |
checksum = sumLuhn(barcode, nParity) | |
return barcode + "#{( 10 - checksum % 10 ) % 10}" | |
end | |
puts checkLuhn1("79927398713") # return ture if valid barcode, return false if invalid barcode | |
puts checkLuhn2("7992739871") # return checkcode |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment