Posted by Vince Wadhwani on Jan 17, 2008

If you're accepting credit cards in your ruby application you may need to use the Mod10 (also known as a Luhn) algorithm to check the final digit. There's sample code to do that in just about every language including ruby. I'll post my snippet below plus reverse it so you can create a check digit too. Why? Because sometimes you need to do that and also because it never hurts to independently verify your check digit with another method. Here goes:

To check to see if your number passes the mod10 check:

def mod10_ok? 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

To actually create a check-digit based on mod10 or Luhn:

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

Thanks to Lou Scoras for helping me refactor and pretty up some of the code.