[QUIZ] Checking Credit Cards (#122)

This is my first submission to Ruby Q…

I have all the credit card rules in an external YAML file. I also think
that my luhn() and type() implementations could be cleaner, but it is
what
it is. :slight_smile:


ccard.yaml

Visa: { starts: [ β€˜4’ ],
sizes: [ 16, 13 ] }
MasterCard: { starts: [ β€˜51’, β€˜52’, β€˜52’, β€˜54’, β€˜55’ ],
sizes: [ 16 ] }
Discover: { starts: [ β€˜6011’ ],
sizes: [ 16 ] }
American Express: { starts: [ β€˜34’, β€˜37’ ],
sizes: [ 15 ] }


ccard.rb

Credit Card Validation

Ruby Q. #122 - Ruby Quiz - Checking Credit Cards (#122)

By Mike M. - http://blowmage.com/

require β€˜yaml’

class CreditCard
def CreditCard.luhn(cc)
multi = 1
nums = cc.gsub(/\D/, β€˜β€™).reverse.split(β€˜β€™).collect do |num|
num = num.to_i * (multi = (multi == 1) ? 2 : 1)
end
total = 0
nums.join.split(β€˜β€™).each do |num|
total += num.to_i
end
total
end

def CreditCard.valid?(cc)
(CreditCard.luhn(cc) % 10) == 0
end

def CreditCard.type(cc)
cc.gsub!(/\D/, β€˜β€™)
YAML::load(open(β€˜ccard.yaml’)).each do |card, rule|
rule[β€˜starts’].each do |start|
if (cc.index(start.to_s) == 0)
return card if rule[β€˜sizes’].index(cc.size)
end
end
end
β€˜Unknown’
end

def initialize(cc)
@number = cc.gsub(/\D/, β€˜β€™)
end

def number
@number
end

def number=(cc)
@number = cc.gsub(/\D/, β€˜β€™)
end

def valid?
CreditCard.valid? @number
end

def type
CreditCard.type @number
end
end

if FILE == $0
cc = CreditCard.new ARGV.join
puts β€œYou entered the following credit card number: #{cc.number}”
puts β€œThe number is for a #{cc.type} credit card”
puts β€œThe number is #{cc.valid? ? β€˜Valid’ : β€˜Not Valid’}”
end