ruby 红宝石的信用卡验证
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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..."
以上是关于ruby 红宝石的信用卡验证的主要内容,如果未能解决你的问题,请参考以下文章
ruby 验证-graphql-红宝石3.rb
ruby 验证-graphql-红宝石2.rb
ruby 验证-graphql-红宝石1.rb
ruby 验证-graphql-红宝石0.rb
ruby 练习:阶级战,验证信用卡号码如果信用卡号码我们应该能够验证它是否有效基于
ruby 练习:阶级战,验证信用卡号码如果信用卡号码我们应该能够验证它是否有效基于