Skip to content

Instantly share code, notes, and snippets.

@rennex
Created January 17, 2019 15:26
Show Gist options
  • Save rennex/b0c8a7212fb31aef98536c54a1478c08 to your computer and use it in GitHub Desktop.
Save rennex/b0c8a7212fb31aef98536c54a1478c08 to your computer and use it in GitHub Desktop.
Luhn's algorithm (calculates the last digit of a credit card number)
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