0

I have the following function:

def valid_credit_card?(number)
    digits = number.scan(/./).map(&:to_i)
    check = digits.pop

    sum = digits.reverse.each_slice(2).map do |x, y|
        [(x * 2).divmod(10), y]
    end.flatten.inject(:+)

    (10 - sum % 10) == check
end

But for some reason I keep getting the following error message: nil can't be coerced into Fixnum

And for some reason I can't figure out why the error is being thrown. Any ideas why this might be happening?

4

1 回答 1

2

digits当元素数量为奇数时,您的方法会失败。在这种情况下,当您调用each_slice(2)最后一次迭代时,x将是 的最后一个元素,digits并且y将是nil. 因此,当您进入inject(:+)阶段时,数组的最后一个元素是nil,并且当解释器遇到类似2 + nil.

为什么不对输入的位数添加初始检查?就像是:

return false unless digits.length == 16
于 2012-10-31T19:54:56.703 回答