ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

Published at Mar 31 2019
·
0 comments

Instructions

Test suite

Solution

Given a number determine whether or not it is valid per the Luhn formula.

The Luhn algorithm is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers and Canadian Social Insurance Numbers.

The task is to check if a given string is valid.

Strings of length 1 or less are not valid. Spaces are allowed in the input, but they should be stripped before checking. All other non-digit characters are disallowed.

```
4539 1488 0343 6467
```

The first step of the Luhn algorithm is to double every second digit, starting from the right. We will be doubling

```
4_3_ 1_8_ 0_4_ 6_6_
```

If doubling the number results in a number greater than 9 then subtract 9 from the product. The results of our doubling:

```
8569 2478 0383 3437
```

Then sum all of the digits:

```
8+5+6+9+2+4+7+8+0+3+8+3+3+4+3+7 = 80
```

If the sum is evenly divisible by 10, then the number is valid. This number is valid!

```
8273 1232 7352 0569
```

Double the second digits, starting from the right

```
7253 2262 5312 0539
```

Sum the digits

```
7+2+5+3+2+2+6+2+5+3+1+2+0+5+3+9 = 57
```

57 is not evenly divisible by 10, so this number is not valid.

For installation and learning resources, refer to the Ruby resources page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

```
gem install minitest
```

If you would like color output, you can `require 'minitest/pride'`

in
the test file, or note the alternative instruction, below, for running
the test file.

Run the tests from the exercise directory using the following command:

```
ruby luhn_test.rb
```

To include color from the command line:

```
ruby -r minitest/pride luhn_test.rb
```

The Luhn Algorithm on Wikipedia http://en.wikipedia.org/wiki/Luhn_algorithm

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

```
require 'minitest/autorun'
require_relative 'luhn'
# Common test data version: 1.4.0 4a80663
class LuhnTest < Minitest::Test
def test_single_digit_strings_can_not_be_valid
# skip
refute Luhn.valid?("1")
end
def test_a_single_zero_is_invalid
skip
refute Luhn.valid?("0")
end
def test_a_simple_valid_sin_that_remains_valid_if_reversed
skip
assert Luhn.valid?("059")
end
def test_a_simple_valid_sin_that_becomes_invalid_if_reversed
skip
assert Luhn.valid?("59")
end
def test_a_valid_canadian_sin
skip
assert Luhn.valid?("055 444 285")
end
def test_invalid_canadian_sin
skip
refute Luhn.valid?("055 444 286")
end
def test_invalid_credit_card
skip
refute Luhn.valid?("8273 1232 7352 0569")
end
def test_valid_number_with_an_even_number_of_digits
skip
assert Luhn.valid?("095 245 88")
end
def test_valid_strings_with_a_non_digit_included_become_invalid
skip
refute Luhn.valid?("055a 444 285")
end
def test_valid_strings_with_a_non_digit_added_at_the_end_become_invalid
skip
refute Luhn.valid?("059a")
end
def test_valid_strings_with_punctuation_included_become_invalid
skip
refute Luhn.valid?("055-444-285")
end
def test_valid_strings_with_symbols_included_become_invalid
skip
refute Luhn.valid?("055Â£ 444$ 285")
end
def test_single_zero_with_space_is_invalid
skip
refute Luhn.valid?(" 0")
end
def test_more_than_a_single_zero_is_valid
skip
assert Luhn.valid?("0000 0")
end
def test_input_digit_9_is_correctly_converted_to_output_digit_9
skip
assert Luhn.valid?("091")
end
def test_strings_with_non_digits_is_invalid
skip
refute Luhn.valid?(":9")
end
end
```

```
class Luhn
def self.valid?(number)
new(number).valid?
end
def initialize(number)
@number = sanitize(number)
end
def valid?
return false if number.length <= 1 || number =~ /\D/
(checksum % 10).zero?
end
private
def sanitize(number)
number.strip.gsub(/\s/, "")
end
def checksum
digits.reverse.each_slice(2).sum do |even, odd = 0|
even + double(odd)
end
end
def digits
number.scan(/\d/).map(&:to_i)
end
def double(digit)
doubled_digit = digit * 2
return doubled_digit if doubled_digit < 10
doubled_digit - 9
end
attr_reader :number
end
```

Things I learned while working on this exercise and want to remember:

1. There's no need to name variables using the type.

2. The naming of a method should hide its complexity. If we want to know more about a method, we can always read it.

3. Using indexes for side effects is a smell.

4. When doing something like sanitizing the input, we don't need to be constantly reminded that the input is sanitized. (This is related to point 2.)

5. Remember that we can pass a block to `#sum`. Also remember to check the documentation for the methods that we are thinking to use, to see what we can do and solidify past knowledge.

6. We can set default values for block arguments: `something.sum do |even, odd = 0|`

7. Don't assume that using `#map` would make something significantly less performant. If worried about performance, use `Benchmark` to check if there really is a significant difference.

Many thanks to `@ajoshguy` for his help.

Level up your programming skills with 3,450 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments