Skip to content

Instantly share code, notes, and snippets.

@trdev7
Last active December 24, 2019 13:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save trdev7/ecdce7b602e2bb749a2c16639ce2a7d8 to your computer and use it in GitHub Desktop.
Save trdev7/ecdce7b602e2bb749a2c16639ce2a7d8 to your computer and use it in GitHub Desktop.
This Ruby file includes Ruby functions that Luhn algorithm is implemented. Function ,"checkLuhn1 check if current barcode(included check digit) validates. Function, "checkLuhn2" returns value that current barcode join with its checkdigit as suffix. /********************************************/ [note] Here, I have used Bitwise Operator instead o…
def sumLuhn (barcode, nParity)
checksum = 0
for i in 0..barcode.length - 1
nDigit = barcode[i].to_i
if nParity == ( i & 1 ) # i % 2
nDigit = ( nDigit << 1 ) # 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 & 1 ) # 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 & 1 ) ) # 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