Created
March 21, 2016 23:47
-
-
Save framallo/4bf5f952418b5102040c to your computer and use it in GitHub Desktop.
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
class Fixnum | |
def digits | |
to_s.split('').map(&:to_i) | |
end | |
def luhn? | |
luhn_checksum % 10 == 0 | |
end | |
def luhn_checksum | |
odd_digits = [] | |
even_digits = [] | |
digits.reverse.each_with_index do |o, i| | |
odd_digits << o if (i+1).odd? | |
even_digits << o if (i+1).even? | |
end | |
total = odd_digits.inject(&:+) | |
even_digits.each do |o| | |
total += (2 * o).digits.inject(&:+) | |
end | |
total | |
end | |
def luhn | |
self * 10 + ((self * 10).luhn_checksum * 9).digits.last | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment