我一直在尝试在 Ruby 中实现 Luhn 算法,但不断收到错误消息,即 nil 不能被合并到 Fixnum 中。
Luhn 算法应该:
从倒数第二个数字开始,每隔一个数字加倍,直到到达第一个数字
将所有未触及的数字和两位数相加(两位数需要分开,10变成1 + 0)
如果总数是十的倍数,则您已收到有效的信用卡号!
这就是我所拥有的:
class CreditCard
def initialize (card_number)
if (card_number.to_s.length != 16 )
raise ArgumentError.new("Please enter a card number with exactly 16 integars")
end
@card_number = card_number
@total_sum = 0
end
def check_card
@new_Array = []
@new_Array = @card_number.to_s.split('')
@new_Array.map! { |x| x.to_i }
@new_Array.each_with_index.map { |x,y|
if (y % 2 != 0)
x = x*2
end
}
@new_Array.map! {|x|
if (x > 9)
x = x-9
end
}
@new_Array.each { |x|
@total_sum = @total_sum + x
}
if (@total_sum % 10 == 0)
return true
else
return false
end
end
end