Module: Verhoeff

Defined in:
lib/verhoeff/verhoeff.rb

Constant Summary collapse

D =
[
  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
  [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
  [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
  [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
  [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
  [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
  [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
  [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
  [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
  [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
]
P =
[
  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
  [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
  [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
  [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
  [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
  [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
  [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
  [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]
]
INV =
[0, 4, 3, 2, 1, 5, 6, 7, 8, 9]
ZERO_ORDINAL =
'0'.each_byte.first

Class Method Summary collapse

Class Method Details

.checksum_digit_of(arg) ⇒ Object



32
33
34
35
36
# File 'lib/verhoeff/verhoeff.rb', line 32

def self.checksum_digit_of(arg)
  INV[arg.to_s.each_byte.reverse_each.enum_for(:each_with_index).inject(0) { |check,(x,i)|
    D[check][P[i.next % 8][x - ZERO_ORDINAL]]
  }]
end

.checksum_of(arg) ⇒ Object



38
39
40
# File 'lib/verhoeff/verhoeff.rb', line 38

def self.checksum_of(arg)
  arg.to_i * 10 + checksum_digit_of(arg)
end

.valid?(num) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/verhoeff/verhoeff.rb', line 42

def self.valid?(num)
  checksum_digit_of(num.to_s[0..-2]) == num.to_s.each_byte.reverse_each.next - ZERO_ORDINAL
end