0

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.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • Not all credit card numbers are 16 digits long ... – Alex K. Sep 26 '14 at 11:37
  • (1111111111111111 is not a valid PAN, are you saying it passes your test?) – Alex K. Sep 26 '14 at 11:37
  • You will be better off treating the PAN as a string only converting the digits to integers for the check digit calculation. – Alex K. Sep 26 '14 at 11:41
  • I'm not saying 11...etc. passes my test or even should. I'm just saying that when it reaches the conditional that is meant to double it, it does nothing. 11111... stays 11111..., or I can get it to work if I remove the else i conditional, but then I get an array that looks like this: [nil, 2, nil, 2, nil, 2, nil, 2]. I got this to work yesterday, I just wanted to know why map was doing this. – Nicholas Dowling Sep 27 '14 at 16:04

0 Answers0