Skip to content

Instantly share code, notes, and snippets.

@pduey
Created March 12, 2013 14:36
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 pduey/5143393 to your computer and use it in GitHub Desktop.
Save pduey/5143393 to your computer and use it in GitHub Desktop.
Ruby method that implements luhn algorithm to validate a number, used by many credit card companies.
#!/usr/bin/env ruby
# Save as file, e.g., luhn_validator.rb, make executable, then: ./luhn_validator.rb 'number'
DIGIT_REDUX = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] # simple lookup instead of doubling and summing if > 9
def valid_luhn_number?(number)
digits = number.to_s.split(//).map{|d| d.to_i}
digits.reverse!.each_index{|i| digits[i] = DIGIT_REDUX[digits[i]] if i.odd?}.reduce(:+) % 10 == 0
end
number = ARGV[0]
puts "#{number} is #{'not ' unless valid_luhn_number?(number)}valid."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment