Skip to content

Instantly share code, notes, and snippets.

@vincentchin
Created September 17, 2015 16:57
Show Gist options
  • Save vincentchin/517461d1c0830d9a1277 to your computer and use it in GitHub Desktop.
Save vincentchin/517461d1c0830d9a1277 to your computer and use it in GitHub Desktop.
require 'minitest/autorun'
module Luhn
def self.is_valid?(number)
digits = number.to_s.split("")
digits.map! {|x| x.to_i }
ary = Array.new
digits.each_with_index do |value, index|
if index.even?
ary << value * 2
else
ary << value
end
end
ary.map! {|x| (x >= 10 ? x-9 : x)}
sum = ary.inject(:+)
if sum % 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