Skip to content

Instantly share code, notes, and snippets.

@adcousin
Forked from henrik/luhn_checksum.rb
Created November 4, 2020 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adcousin/1e7e429118f1dd8c1b53555608f7c0f6 to your computer and use it in GitHub Desktop.
Save adcousin/1e7e429118f1dd8c1b53555608f7c0f6 to your computer and use it in GitHub Desktop.
Luhn checksum/check digit generation in Ruby.
class Luhn
def self.checksum(number)
digits = number.to_s.reverse.scan(/\d/).map { |x| x.to_i }
digits = digits.each_with_index.map { |d, i|
d *= 2 if i.even?
d > 9 ? d - 9 : d
}
sum = digits.inject(0) { |m, x| m + x }
mod = 10 - sum % 10
mod==10 ? 0 : mod
end
end
# Luhn.checksum(123) # => 0
# Luhn.checksum(456) # => 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment