I've been trying to implement the Luhn Algorithm in Ruby but keep getting the error message that nil cannot be corerced into Fixnum.
The Luhn Algorithm is supposed to:
Starting with the second to last digit, double every other digit until you reach the first digit
Sum all the untouched digits and the doubled digits (doubled digits need to be broken apart, 10 becomes 1 + 0)
If the total is a multiple of ten, you have received a valid credit card number!
This is what I have:
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
=>
or you can also write
Without
else
clause value ofif false; ...; end
will always benil