Skip to content

Instantly share code, notes, and snippets.

@bstolte
Created October 21, 2015 18:08
Show Gist options
  • Save bstolte/5be31d05cdac613c6920 to your computer and use it in GitHub Desktop.
Save bstolte/5be31d05cdac613c6920 to your computer and use it in GitHub Desktop.
Luhn Algorithm - validate credit card numbers
require 'minitest/autorun'
module Luhn
# number must be a string
# number = number.to_s
def self.is_valid?(number)
array = number.to_s.split('')
array = array.reverse
array = array.map.with_index do |x, i|
x = x.to_i
# for the last item in the list, i = 0
if i % 2 == 1
x = x * 2
if x >= 10
x = x - 9
end
end
x
end
array = array.inject(:+)
if array % 10 == 0
return true
else
return false
end
end
end
class TestLuhn < MiniTest::Unit::TestCase
def test_luhn_valid
assert Luhn.is_valid?(4194560385008504)
end
def test_luhn_invalid
assert ! Luhn.is_valid?(4194560385008505)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment