-
-
Save jrgifford/6e3cfb2f3edb645fc804 to your computer and use it in GitHub Desktop.
credit card validation on ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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..." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment