Skip to content

Instantly share code, notes, and snippets.

@sairam
Forked from tinogomes/gist:1182499
Created September 11, 2011 16:38
Show Gist options
  • Save sairam/1209799 to your computer and use it in GitHub Desktop.
Save sairam/1209799 to your computer and use it in GitHub Desktop.
credit card validation on ruby
# 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