Skip to content

Instantly share code, notes, and snippets.

@Niall47
Last active November 24, 2021 17:45
Show Gist options
  • Save Niall47/6824732d0fc2ca73831e1602087f9a9b to your computer and use it in GitHub Desktop.
Save Niall47/6824732d0fc2ca73831e1602087f9a9b to your computer and use it in GitHub Desktop.
=begin
Luhn check
The Luhn check is a simple checksum, famously used to check credit card numbers are at least possibly valid.
Take this number:
4539 3195 0343 6467
The first thing we do is, starting on the right, double every second number and, if that number is greater than 9, subtract 9 from it:
4539319503436467
^ ^ ^ ^ ^ ^ ^ ^
8569 6195 0383 3437
The next step is to add all the digits:
8+5+6+9+6+1+9+5+0+3+8+3+3+4+3+7 = 80
If the sum is evenly divisible by 10 then the number is valid.
Another example:
8273 1232 7352 0569
^ ^ ^ ^ ^ ^ ^ ^
7+2+5+3+2+2+6+2+5+3+1+2+0+5+3+9 = 57
57 is not evenly divisible by 10 so it is invalid.
=end
cc = ARGV.first
return_array = []
def maths(number)
# we've already doubled it, so we either return it minus 9 or as it is
number > 9 ? number - 9 : number
end
# prepare the array by removing spaces and converting our string to an array of integers
int_array = cc.delete(' ').chars.map(&:to_i).reverse
# We populate the return array with the original number or the result of the maths method depending on the index being odd or even
int_array.each_with_index { |digit, index| return_array << (index.odd? ? maths(digit * 2) : digit) }
puts return_array.sum
return_array.sum.even? ? (puts 'valid') : (puts 'invalid')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment