Module: LuhnChecker

Defined in:
lib/active_validators/active_model/validations/shared/luhn_checker.rb

Class Method Summary collapse

Class Method Details

.valid?(s) ⇒ Boolean

This method implements Luhn algorythm. Details about it’s work may be founded here: en.wikipedia.org/wiki/Luhn_Algorithm

Returns:

  • (Boolean)


4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/active_validators/active_model/validations/shared/luhn_checker.rb', line 4

def self.valid?(s)
  value = s.gsub(/\D/, '').reverse

  sum = i = 0

  value.each_char do |ch|
    n = ch.to_i

    n *= 2 if i.odd?

    n = 1 + (n - 10) if n >= 10

    sum += n
    i   += 1
  end

  (sum % 10).zero?
end