Skip to content

Instantly share code, notes, and snippets.

@shwoodard
Created March 1, 2014 19:48
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 shwoodard/9296055 to your computer and use it in GitHub Desktop.
Save shwoodard/9296055 to your computer and use it in GitHub Desktop.
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