Last active
April 16, 2016 14:22
-
-
Save aruponse/7ccf3326746f70ef7a8d35d596eba531 to your computer and use it in GitHub Desktop.
Algoritmo de Luhn (Ruby)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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