Skip to content

Commit 9f3bea5

Browse files
author
Kimmie
committed
Add method to check if a value is valid based on Luhn Algorithm
1 parent 9935c4d commit 9f3bea5

File tree

2 files changed

+60
-4
lines changed

2 files changed

+60
-4
lines changed

lib/luhn_algorithm.rb

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
require 'luhn_algorithm/version'
22

33
module LuhnAlgorithm
4-
class Error < StandardError; end
5-
# Your code goes here...
4+
NUMBER_ONLY = /^\d+$/
5+
6+
def self.valid?(value)
7+
value = value.to_s.reverse
8+
return false unless value.match(NUMBER_ONLY)
9+
arr = value.chars.map(&:to_i)
10+
(1...(arr.length)).step(2) do |index|
11+
arr[index] = (arr[index] * 2).divmod(10).sum
12+
end
13+
(arr.sum % 10).zero?
14+
end
615
end

spec/luhn_algorithm_spec.rb

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,54 @@
33
expect(LuhnAlgorithm::VERSION).not_to be nil
44
end
55

6-
it "does something useful" do
7-
expect(false).to eq(true)
6+
[
7+
{
8+
value: '6011111111111117',
9+
result: true
10+
},
11+
{
12+
value: '6011111111111118',
13+
result: false
14+
},
15+
{
16+
value: 4222222222222,
17+
result: true
18+
},
19+
{
20+
value: '4222221222222',
21+
result: false
22+
},
23+
{
24+
value: '4522222222222',
25+
result: false
26+
},
27+
{
28+
value: '4522222222222',
29+
result: false
30+
},
31+
{
32+
value: '45222222222220',
33+
result: false
34+
},
35+
{
36+
value: '45222222222220',
37+
result: false
38+
},
39+
{
40+
value: '4111111111111111',
41+
result: true
42+
},
43+
{
44+
value: 'A122333333333',
45+
result: false
46+
},
47+
{
48+
value: 6011000990139424,
49+
result: true
50+
}
51+
].each do |hs|
52+
it "return #{hs[:result]} for value #{hs[:value]}" do
53+
expect(LuhnAlgorithm.valid?(hs[:value])).to eq(hs[:result])
54+
end
855
end
956
end

0 commit comments

Comments
 (0)