Module: Validatr::Luhn

Extended by:
Utils
Defined in:
lib/validatr/luhn.rb

Class Method Summary collapse

Methods included from Utils

digits_from_number

Class Method Details

.check_digit(number, n = 10) ⇒ Object



13
14
15
16
17
18
# File 'lib/validatr/luhn.rb', line 13

def self.check_digit(number, n = 10)
  digits = digits_from_number(number)
  digits.push(0)
  sum = sum_digits(digits)
  (sum * 9) % n
end

.sum_digits(digits) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'lib/validatr/luhn.rb', line 20

def self.sum_digits(digits)
  digits.reverse.map.with_index do |d, i|
    if i.even?
      d
    else
      (d < 5 ? (d * 2) : ((d * 2) % 10) + 1)
    end
  end.inject(:+)
end

.valid?(number, n = 10) ⇒ Boolean

Returns:

  • (Boolean)


7
8
9
10
11
# File 'lib/validatr/luhn.rb', line 7

def self.valid?(number, n = 10)
  digits = digits_from_number(number)
  sum = sum_digits(digits)
  (sum % n).zero?
end