Created
May 9, 2012 06:49
-
-
Save momo-lab/2642521 to your computer and use it in GitHub Desktop.
Luhnアルゴリズムの実装サンプル
This file contains hidden or 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
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