Created
September 17, 2015 16:57
-
-
Save vincentchin/517461d1c0830d9a1277 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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