#!/usr/bin/env ruby
def checksum(idnum)
w = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
r = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"]
if [17, 18].include?(idnum.length) then
sum = 0
(0..16).each do |i|
begin
sum += w[i] * Integer(idnum[i, 1])
rescue ArgumentError
return false, "ERROR: Invalid ID: #{idnum}, at position: #{i} [#{idnum[i, 1]}]"
end
end
csd = r[sum % 11]
if idnum.length == 17 then
return true, csd
elsif csd == idnum[17, 1] then
return true, csd
else
return false, "ERROR: Invalid ID: #{idnum}, checksum expected: #{csd}, given: #{idnum[17, 1]}"
end
else
return false, "ERROR: Invalid ID: #{idnum}, length: #{idnum.length}, expected: 17 or 18"
end
end
if ARGV.length == 1 then
idnum = ARGV[0]
res, msg = checksum(idnum)
if res then
idnum += msg if idnum.length == 17
puts "Valid ID: #{idnum}, checksum digit: #{msg}"
else
puts msg
end
else
puts "USAGE: #{$0} ID-number"
end
没有评论:
发表评论