Skip to content

Instantly share code, notes, and snippets.

@listrophy
Created May 17, 2012 22:56
Show Gist options
  • Save listrophy/2722143 to your computer and use it in GitHub Desktop.
Save listrophy/2722143 to your computer and use it in GitHub Desktop.
Credit card number validator?
# Do NOT assume this is production code.
class String
def to_is
self.chars.map(&:to_i)
end
end
def luhn cc
cc.
reverse.
to_is.
each_with_index.
map{|a,b|(a*(b%2+1)).to_s}.
join.
to_is.
inject(&:+) % 10 == 0
end
def valid cc, len
cc.length == len && luhn(cc)
end
cc = ARGV[0]
n = case cc
when /^34/, /^37/
puts 'AMEX'; 15
when /^6011/
puts 'Discover'; 16
when /^5[1-5]/
puts 'MasterCard'; 16
when /^4/
puts 'Visa'; [13, 16]
else
puts 'Unknown'; -1
end
puts (Array(n).any?{|len| valid(cc, len)} ? 'Valid' : 'Invalid')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment