public
Last active

credit card validation on ruby

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
# References
# http://en.wikipedia.org/wiki/Bank_card_number
# http://en.wikipedia.org/wiki/Luhn_algorithm
 
def valid_credit_card?(number)
number = number.to_s.gsub(/\D/, "")
 
return false unless valid_association?(number)
number.reverse!
 
relative_number = {'0' => 0, '1' => 2, '2' => 4, '3' => 6, '4' => 8, '5' => 1, '6' => 3, '7' => 5, '8' => 7, '9' => 9}
 
sum = 0
 
number.split("").each_with_index do |n, i|
sum += (i % 2 == 0) ? n.to_i : relative_number[n]
end
 
sum % 10 == 0
end
 
def valid_association?(number)
number = number.to_s.gsub(/\D/, "")
 
return :dinners if number.length == 14 && number =~ /^3(0[0-5]|[68])/ # 300xxx-305xxx, 36xxxx, 38xxxx
return :amex if number.length == 15 && number =~ /^3[47]/ # 34xxxx, 37xxxx
return :visa if [13,16].include?(number.length) && number =~ /^4/ # 4xxxxx
return :master if number.length == 16 && number =~ /^5[1-5]/ # 51xxxx-55xxxx
return :discover if number.length == 16 && number =~ /^6011/ # 6011xx
return nil
end
 
while(true)
print ">> "
begin
number = gets.chomp
rescue NoMethodError => e
puts ""
number = "exit"
end
break if number == "exit"
puts "#{number} is #{valid_credit_card?(number) ? valid_association?(number) : 'frauld'}"
end
 
puts "Bye..."

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.