Forum: Ruby #122 Credit Card Validator (solution)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Pieter V. (Guest)
on 2007-05-03 07:03
(Received via mailing list)
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)
This topic is locked and can not be replied to.