Last active
December 9, 2015 19:21
-
-
Save framallo/dc337fd6f37185ef1825 to your computer and use it in GitHub Desktop.
This file contains hidden or 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' | |
require 'pp' | |
module Luhn | |
def self.is_valid?(number) | |
each_digit(number).reverse.map.with_index do |e, i| | |
r = e.to_i | |
r *= 2 if i.odd? | |
r -= 9 if r >= 10 | |
r | |
end.inject(&:+) % 10 == 0 | |
end | |
private | |
def self.each_digit(number) | |
number.to_s.each_char.to_a | |
end | |
end | |
class TestLuhn < MiniTest::Unit::TestCase | |
def test_luhn_valid | |
assert Luhn.is_valid?(4_194_560_385_008_504), 'has a valid number' | |
end | |
def test_luhn_invalid | |
assert !Luhn.is_valid?(4_194_560_385_008_505), 'has a valid number' | |
end | |
def test_luhn_valid2 | |
assert Luhn.is_valid?(377_681_478_627_336), | |
'Check step two: Did you start at the right?' | |
end | |
def test_luhn_invalid2 | |
assert !Luhn.is_valid?(377_681_478_627_337), | |
'Check step two: Did you start at the right?' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment