Skip to content

Instantly share code, notes, and snippets.

@tinogomes
Last active September 24, 2021 05:48
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tinogomes/1182499 to your computer and use it in GitHub Desktop.
credit card validation on ruby
# MIT License
# Copyright (c) 2011 Celestino Ferreira Gomes
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# 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