Skip to content

Instantly share code, notes, and snippets.

@randito
Created August 17, 2011 16:13
Show Gist options
  • Save randito/1151896 to your computer and use it in GitHub Desktop.
Save randito/1151896 to your computer and use it in GitHub Desktop.
Luhn algorithm (valid CC check)
# Luhn algorithm to determine if a CC is valid
def valid(cc)
return false unless cc.respond_to?(:to_i) && cc.to_i != 0
doubled = []
cc.reverse.each_char.each_with_index do |c,i|
v = (i % 2 == 0) ? c.to_i : c.to_i * 2
doubled << v
end
summed = doubled.map do |d|
d.to_s.each_char.inject(0) { |sum, n| sum + n.to_i }
end
total = summed.inject(0) { |sum, n| sum + n }
total % 10
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment