Created
March 12, 2013 14:36
-
-
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.
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
#!/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