Skip to content

Instantly share code, notes, and snippets.

@aruponse
Last active April 16, 2016 14:22
Show Gist options
  • Save aruponse/7ccf3326746f70ef7a8d35d596eba531 to your computer and use it in GitHub Desktop.
Save aruponse/7ccf3326746f70ef7a8d35d596eba531 to your computer and use it in GitHub Desktop.
Algoritmo de Luhn (Ruby)
def is_valid?(number)
digits = number.to_s.reverse.chars.map(&:to_i)
check_sum = 0
digits.each_slice(2) do |odd, even|
check_sum += odd
next unless even
even *= 2
even = even.divmod(10).inject(:+) if even > 9
check_sum += even
end
return check_sum.modulo(10) == 0
end
def generate(number)
digits = number.to_s.reverse.chars.map(&:to_i)
check_sum = 0
digits.each_slice(2) do |odd, even|
odd *= 2
odd = odd.divmod(10).inject(:+) if odd > 9
check_sum += odd
next unless even
check_sum += even
end
verificator= (check_sum*9).modulo(10)
return (number.to_s + verificator.to_s)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment