Created
October 21, 2016 21:37
-
-
Save kenmazaika/9aa3ae9b517c00ae697cce0acb35dde4 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
| module Luhn | |
| def self.is_valid?(num) | |
| digits = num.to_s.split("").collect(&:to_i) | |
| new_digits = [] | |
| digits.reverse.each_with_index do |digit, index| | |
| if index % 2 == 1 | |
| digit = digit * 2 | |
| digit = digit - 9 if digit >= 10 | |
| end | |
| new_digits << digit | |
| end | |
| new_digits.inject(&:+) % 10 == 0 | |
| end | |
| end | |
| puts "#{Luhn.is_valid?(4194560385008504)} - true" | |
| puts "#{Luhn.is_valid?(4194560385008505)} - false" | |
| puts "#{Luhn.is_valid?(377681478627336)} - true" | |
| puts "#{Luhn.is_valid?(377681478627337)} - false" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment