Skip to content

Instantly share code, notes, and snippets.

@jamielennox
Created January 15, 2013 23:23
Show Gist options
  • Save jamielennox/4543115 to your computer and use it in GitHub Desktop.
Save jamielennox/4543115 to your computer and use it in GitHub Desktop.
#!/bin/ruby
##
# Take a credit card number and determine the type of card
#
# @param [String] card the card number
# @return [String] the card type.
#
def card_type(card)
if card =~ /^3[47]\d+$/ && card.length == 15
'AMEX'
elsif card =~ /^6011\d+$/ && card.length == 16
'Discover'
elsif card =~ /^5[1-5]\d+$/ && card.length == 16
'MasterCard'
elsif card =~ /^4\d+$/ && [13, 16].include?(card.length)
'VISA'
else
'Unknown'
end
end
##
# Verify if a credit card number matches the Luhn algorithm.
#
# @param [String] card the card number
# @return [Boolean] true if the card verifies.
#
def luhn_verify?(card)
total = 0
card.reverse.each_char.with_index do |num,idx|
total += if idx % 2 == 0
num.to_i
else
n = num.to_i * 2
n >= 10 ? n % 10 + 1 : n
end
end
total % 10 == 0
end
#
# There isn't much information about input methods/validation so lets just have it loaded.
#
if __FILE__ == $0
DATA.each_line do |card|
card.gsub!(/\s/, '')
puts "#{card_type card}: #{card} (#{luhn_verify?(card) ? 'valid' : 'invalid'})"
end
end
__END__
4111111111111111
4111111111111
4012888888881881
378282246310005
6011111111111117
5105105105105100
5105 1051 0510 5106
9111111111111111
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment