Skip to content

Instantly share code, notes, and snippets.

@kenmazaika
Created October 21, 2016 21:37
Show Gist options
  • Save kenmazaika/9aa3ae9b517c00ae697cce0acb35dde4 to your computer and use it in GitHub Desktop.
Save kenmazaika/9aa3ae9b517c00ae697cce0acb35dde4 to your computer and use it in GitHub Desktop.
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