Module: Gtiny::CheckDigitCalculators

Defined in:
lib/gtiny/check_digit_calculators.rb

Overview

Module containing check digit algorithms for various encodings.

Class Method Summary collapse

Class Method Details

.gs1(digits) ⇒ String

Calculate the check digit for any GTIN or ISBN-13.

There’s a great visualization of this algorithm here: www.gs1.org/services/how-calculate-check-digit-manually

Parameters:

  • digits (String)
    • the barcode digits (without the check digit)

Returns:

  • (String)
    • the computed check digit



13
14
15
16
17
18
19
20
21
# File 'lib/gtiny/check_digit_calculators.rb', line 13

def self.gs1(digits)
  sum = digits.reverse.each_char.with_index.sum do |digit, idx|
    multiplier = (idx % 2).zero? ? 3 : 1
    multiplier * digit.to_i
  end

  check_digit = (10 - sum) % 10
  check_digit.to_s
end

.isbn10(digits) ⇒ String

Calculate the check digit for any ISBN-10.

Some information on the algorithm is available here: en.wikipedia.org/wiki/ISBN#ISBN-10_check_digits

Parameters:

  • digits (String)
    • the barcode digits (without the check digit)

Returns:

  • (String)
    • the computed check digit



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/gtiny/check_digit_calculators.rb', line 30

def self.isbn10(digits)
  sum = digits.reverse.each_char.with_index.sum do |digit, idx|
    multiplier = idx + 2
    multiplier * digit.to_i
  end

  # Since ISBN-10 uses mod 11 to calculate the check digit, the last digit
  # can be 10, which is represented with an 'x'.
  check_digit = (11 - sum) % 11
  check_digit == 10 ? "x" : check_digit.to_s
end