Created
January 17, 2019 15:26
-
-
Save rennex/b0c8a7212fb31aef98536c54a1478c08 to your computer and use it in GitHub Desktop.
Luhn's algorithm (calculates the last digit of a credit card number)
This file contains 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
def luhn_calc(num) | |
sum = 0 | |
num.to_s.gsub(/\s/, "").each_char.to_a.reverse.each_with_index do |d,i| | |
multiplier = 2 - (i&1) | |
sum += (multiplier * d.to_i).divmod(10).reduce(:+) | |
end | |
sum * 9 % 10 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment