Created
August 27, 2015 17:00
-
-
Save charger/7c9910feb5b0b626ccd3 to your computer and use it in GitHub Desktop.
Luhn algorythm
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
#https://en.wikipedia.org/wiki/Luhn_algorithm | |
# v1 | |
def self.check_digit_for(number) | |
digits = number.to_s.reverse.split(//) | |
sum = 0 | |
digits.each_with_index do |digit, index| | |
digit = digit.to_i | |
digit *= 2 if index.even? | |
digit -= 9 if digit > 9 | |
sum += digit | |
end | |
mod = 10 - sum % 10 | |
mod == 10 ? 0 : mod | |
end | |
# v2 | |
def self.check_digit_for(number) | |
digits = account_number.scan(/./).map(&:to_i) | |
sum = digits.reverse.each_slice(2).map do |x, y| | |
[(x * 2).divmod(10), y || 0] | |
end.flatten.inject(:+) | |
(10 - sum % 10) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment