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.
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