Skip to content

Instantly share code, notes, and snippets.

@elixirdada
Forked from trdev7/calcChecksum.rb
Created November 5, 2018 20:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elixirdada/46ae2fced574d50bc8ee734f1b9c9711 to your computer and use it in GitHub Desktop.
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.
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