# \#122 Credit Card Validator (solution)

**URL:** <https://www.ruby-forum.com/t/122-credit-card-validator-solution/103229>\
**Category:** Ruby\
**Created:** [May 3, 2007, 5:03am UTC](https://www.ruby-forum.com/t/122-credit-card-validator-solution/103229 "2007-05-03T05:03:45Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![illusoft](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/94ad74/32.png) [@illusoft](https://www.ruby-forum.com/u/illusoft)\
**Post date:** [May 3, 2007, 5:03am UTC](https://www.ruby-forum.com/t/122-credit-card-validator-solution/103229/1 "2007-05-03T05:03:45Z")

</div>

It’s a hack job, nothing terribly pretty or well abstracted, but it  
certainly hits the 80% mark.

* * *

num = ARGV.join

def luhn(number)  
double = true  
luhn = 0  
number.scan(/./) do |digit|  
n = digit.to\_i \* (double ? 2 : 1)  
luhn += n % 10 + n / 10  
double = !double  
end  
(luhn % 10) == 0  
end

def type(number)  
case number  
when /^34|37[0-9]{13}/ then “AMEX”  
when /^6011[0-9]{12}/ then “Discover”  
when /^5[1-5][0-9]{14}/ then “MasterCard”  
when /^4([0-9]{12}|[0-9]{15})/ then “Visa”  
else “Unknown”  
end  
end

puts “Type: %s” % type(num)  
puts “Valid: %s” % (luhn(num) ? :true : :false)
