Ruby Luhn check (aka mod 10) formula

I just rolled my own method for checking credit card digits:


def check_digits? num
  odd = true
  num.to_s.gsub(/\D/,'').reverse.split('').map(&:to_i).collect { |d|
    d *= 2 if odd = !odd
    d > 9 ? d - 9 : d
  }.sum % 10 == 0
end

ADDENDUM: Rick Hull’s comments from this blog post helped me remove a dependency on map_with_index

PS: the symbol#to_proc and Enumerable#sum are Rails add-ons…

Sorry, comments are closed for this article.