Skip to content

Instantly share code, notes, and snippets.

@framallo
Last active December 9, 2015 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save framallo/dc337fd6f37185ef1825 to your computer and use it in GitHub Desktop.
Save framallo/dc337fd6f37185ef1825 to your computer and use it in GitHub Desktop.
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