So I am Having some problems when applying Luhn algorithm Here are the general rules: http://www.codeproject.com/Tips/515367/Validate-credit-card-number-with-Mod-algorithm
and here is my code
def luhn(credit_card)
result = 0
nums = credit_card.split("")
nums.each_with_index do |item, index|
if index.even?
if item.to_i*2>9
result+= item.to_i*2-9
else
result+= item.to_i*2
end
else
result +=item.to_i
end
end
if (result % 10) == 0
self.validation = "valid"
else
self.validation = "invalid"
end
end
It works on the majority of cards
VISA: 4111111111111111 (valid)
VISA: 4111111111111 (invalid)
VISA: 4012888888881881 (valid)
Discover: 6011111111111117 (valid)
MasterCard: 5105105105105100 (valid)
MasterCard: 5105105105105106 (invalid)
Unknown: 9111111111111111 (invalid)
But when it comes to this one
AMEX: 37828224631000(invalid)
For some reason my code says its not valid,but it should be according to the official testing card list.
I have seen a bunch of other codes that are working but I want to correct the mistake and understand my mistake. I will appreciate some explanation why is it working like this.