Skip to content

Instantly share code, notes, and snippets.

@glongman
Created September 16, 2010 13:13
Show Gist options
  • Save glongman/582403 to your computer and use it in GitHub Desktop.
Save glongman/582403 to your computer and use it in GitHub Desktop.
require 'test/unit'
class LuhnTest < Test::Unit::TestCase
def luhn_valid?(s)
return false unless s && s.is_a?(String)
return false if s.empty?
value = s.gsub(/\D/, '')
return false if value.empty?
value.
reverse.
each_char.
collect(&:to_i).
each_with_index.
inject(0) {| num, (i, index) |
num + if (index + 1) % 2 == 0
i*=2; ((i > 9) ? (i % 10) + 1 : i)
else
i
end
} % 10 == 0
end
def test_nil_or_empty_string
check_invalid nil
check_invalid ""
end
def test_no_digits_is_not_valid
check_invalid "foo"
end
def test_should_not_be_valid
# 0 1 2 3 4 5 6 7 8 9
# 0 1 4 3 8 5 12 7 16
#--------------------------
# 0 + (1) + (4) + (3) + (8) + (5) + (1+2) + (7) + (1+6) + 9 = 47 % 10 = 7 NOT VALID
check_invalid '0123456789'
# 1 2 3 4 5 6 7 8 9
# 1 4 3 8 5 12 7 16
#--------------------------
# (1) + (4) + (3) + (8) + (5) + (1+2) + (7) + (1+6) + 9 = 47 % 10 = 7 NOT VALID
check_invalid '123456789'
# 1 2 0 2 3 4 5 6 7 8 8 1
# 1 4 0 2 6 4 10 6 14 8 16
#-----------------------------------
# (1) + (4) + (0) + (2) + (6) + (4) + (1+0) + (6) + (1+4) + (8) + (1+6) + 1 = 45 % 10 = 5 NOT VALID
check_invalid '1 2 0 2 3 4 5 6 7 8 9 1'
end
def test_should_be_valid
# 9 3 8 9 7 0 2 3 5 9
# 18 3 16 9 14 0 4 3 10
#-----------------------------
# (1+8) + 3 + (1+6) + 9 + (1+4) + 0 + 4 + 3 + (1+0) + 9 = 50 % 10 VALID
check_valid '9389702359'
check_valid '9389 702 359'
check_valid '9389 - 702 - 359'
# 5 1 0 5 1 0 5 1 0 5 1 0 5 1 0 0
# 10 1 0 5 2 0 10 1 0 5 2 0 10 1 0
#-----------------------------------------------
# (1+0) + 1 + 0 + 5 + 2 + 0 + (1+0) + 0 + 5 + 2 + (1+0) + 1 + 0 + = 20 % 10 = 0 VALID
check_valid '5105 1051 0510 5100'
# 3 4 0 0 0 0 0 0 0 0 0 0 0 0 9
# 3 8 0 0 0 0 0 0 0 0 0 0 0 0
#--------------------------
# (3) + (8) + a whack load of zeros + 9 = 20 % 0 = VALID
check_valid '3400 0000 0000 009'
# 3 7 0 0 0 0 0 0 0 0 0 0 0 0 2
# 3 14 0 0 0 0 0 0 0 0 0 0 0 0
#-----------------------------------
# 3 + (1 + 4) + 2 = 10 % 10 = 0 VALID!
check_valid '3700 0000 0000 002'
end
def check_valid(string)
assert luhn_valid?(string), "INVALID: #{string} (should be valid)"
end
def check_invalid(string)
assert !luhn_valid?(string), "VALID: #{string} (should be invalid)"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment