Skip to content

Instantly share code, notes, and snippets.

@msarit
Created April 9, 2018 12:54
Show Gist options
  • Save msarit/8eb64c99e805f5c5b644720bf07372a5 to your computer and use it in GitHub Desktop.
Save msarit/8eb64c99e805f5c5b644720bf07372a5 to your computer and use it in GitHub Desktop.
module Luhn
def self.is_valid?(number)
array = number.to_s.chars.map(&:to_i)
array2 = []
array.reverse.each_with_index do |digit,digit_index|
if digit_index % 2 == 1
digit = digit * 2
if digit >= 10
digit = digit - 9
end
end
array2 << digit
end
sum = array2.inject(0){ |total,x| total + x }
return true if sum % 10 == 0
return false if sum % 10 != 0
end
end
# Test Numbers:
# 4194560385008504/5
# 377681478627336/7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment