Skip to content

Instantly share code, notes, and snippets.

@rubyrider
Created April 21, 2014 03:40
Show Gist options
  • Save rubyrider/11131585 to your computer and use it in GitHub Desktop.
Save rubyrider/11131585 to your computer and use it in GitHub Desktop.
Luhn Algorithm
def number_with_check_digits(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
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
number.coerce(mod).reverse.join.to_i
end
def credit_card_valid?(account_number)
digits = account_number.to_s.scan(/./).map(&:to_i) # account_number could be a integer as well
check = digits.pop
sum = digits.reverse.each_slice(2).map do |x, y|
[(x * 2).divmod(10), y || 0]
end.flatten.inject(:+)
(10 - sum % 10) == check
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment