Created
March 1, 2014 19:48
-
-
Save shwoodard/9296055 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
class Bank::LuhnValidator | |
def self.valid_credit_card_number?(card_number) | |
valid = true | |
# Input requirements dictate that the card_number | |
# be numeric and that it be upto 19 characters | |
valid &= card_number.is_a?(Integer) && | |
(1..19).cover?(card_number.to_s.size) | |
valid &= luhn_valid?(card_number) | |
valid | |
end | |
def self.luhn_valid?(card_number) | |
digits = card_number.to_s.split('').map(&:to_i) | |
digits.reverse! | |
i = 0 | |
luhn_sum = digits.inject(0) do |sum, curr_digit| | |
curr_digit *= 2 if i.odd? | |
sum += sum_digits(curr_digit) | |
i += 1 | |
sum | |
end | |
(luhn_sum % 10).zero? | |
end | |
private | |
def self.sum_digits(num) | |
num.to_s.split('').map(&:to_i).inject {|sum, x| sum + x } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment