Skip to content

Instantly share code, notes, and snippets.

@momo-lab
Created May 9, 2012 06:49
Show Gist options
  • Save momo-lab/2642521 to your computer and use it in GitHub Desktop.
Save momo-lab/2642521 to your computer and use it in GitHub Desktop.
Luhnアルゴリズムの実装サンプル
module Luhn
CODE_0 = "0".ord
CODE_9 = "9".ord
CODE_A = "A".ord
CODE_Z = "Z".ord
def self.add(data)
return data + get_char(data)
end
def self.check(data)
return (calculate(data) % 10) == 0
end
def self.get_char(data)
return ((10 - (calculate(data + "0") % 10)) % 10).to_s
end
private
def self.calculate(data)
sum = 0
flag = (data.length % 2 == 0)
data.each_byte.with_index do |ch, i|
if CODE_0 <= ch && ch <= CODE_9
num = ch - CODE_0
elsif CODE_A <= ch && ch <= CODE_Z
num = ch - CODE_A + 10
else
raise ArgumentError
end
num *= 2 if flag
if num > 9
num = (num % 10) + (num / 10)
end
sum += num
flag = !flag
end
return sum
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment