Skip to content

Instantly share code, notes, and snippets.

@dan-manges
Created June 8, 2010 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dan-manges/429398 to your computer and use it in GitHub Desktop.
Save dan-manges/429398 to your computer and use it in GitHub Desktop.
def self.luhn_valid?(number)
return false unless number.to_s =~ /\A\d+\z/
digits = number.scan(/\d/).map(&:to_i).reverse
digits.each_with_index do |digit, index|
if index.odd?
digits[index] = (digit >= 5 ? digit * 2 - 9 : digit * 2)
end
end
digits.sum % 10 == 0
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment