Created
July 13, 2018 00:34
-
-
Save zailleh/2843899e857567a5e5757bc75096a8c1 to your computer and use it in GitHub Desktop.
Monkey Patch for the Integer class in Ruby to add Luhn algorithm features.
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 Integer | |
def luhn_sum | |
num = self.to_s.chars | |
sum = 0 | |
num.reverse.each_with_index do |n,i| | |
n = n.to_i | |
n *= 2 if i % 2 == 1 | |
n -= 9 if n >= 10 | |
sum += n | |
end | |
sum | |
end | |
def luhn_valid? | |
sum = luhn_sum | |
if sum % 10 == 0 | |
true | |
else | |
false | |
end | |
end | |
def make_valid_luhn | |
if luhn_valid? | |
puts "Already Valid" | |
self | |
else | |
num = self*10 | |
num + (num.luhn_sum * 9).to_s[-1].to_i | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment