So I'm trying to verify a credit card number by using a simple algorithm. I'm able to get some numbers through, but not all numbers, and I can't figure out why.
class CreditCard
def initialize(number)
@number = (number.to_s.split("")).map! { |i| i.to_i}
if @number.length != 16
raise ArgumentError, "Not a valid credit card number"
end
end
def check_card()
@number.reverse!.map! do |i|
if @number.index(i).odd?
i * 2
else
i
end
end
p "Here is my array: #{@number}"
# split method
# @number.map! do |num|
# if num >= 10
# num = num.to_s.split("").map! { |i| i.to_i }
# else
# num
# end
# end
# @number.flatten!
#sum method
# @number = @number.flatten!.inject(0) { |sum, element| sum + element}
# if @number % 10 == 0
# return true
# else
# return false
# end
end
end
When I pass 6789678967896781(an integer, not a string) each method works. When I pass 1111111111111111, it doesn't work. I'm working back through all my (admittedly messy) code and I found that when control hits this:
@number.reverse!.map! do |i|
if @number.index(i).odd?
i * 2
else
i
end
end
The output is simply an array with 16 ones. The remaining code has been commented out because I couldn't pass each test in rspec, so I started working backwards. I plan to try and make the split and add methods private methods which are both called by the check_card method. I really think I need a second pair of eyes on this. I'm just missing something. Hopefully it's a minnow and not a whale.