Created
August 17, 2011 16:13
-
-
Save randito/1151896 to your computer and use it in GitHub Desktop.
Luhn algorithm (valid CC check)
This file contains hidden or 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
# 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