Module: Sjekksum::ISBN13

Extended by:
ISBN13, Shared
Included in:
ISBN13
Defined in:
lib/sjekksum/isbn13.rb

Overview

Module for calculation and validation of ISBN-10 (International Standard Book Number) checksums

Its check digit is generated the same way as the UPC except that the even digits are multiplied by 3 instead of the odd digits.

Instance Method Summary collapse

Instance Method Details

#convert(number) ⇒ Integer, String Also known as: transform

Transforms a number by appending the ISBN13 checksum digit

It will preserve type (Integer/String) and therefore leading zeros.

Examples:

Sjekksum::ISBN13.convert("978-0-306-40615-") #=> "978-0-306-40615-7"

Parameters:

  • number (Integer, String)

    number without a checksum

Returns:

  • (Integer, String)

    final number including the checksum


61
62
63
64
# File 'lib/sjekksum/isbn13.rb', line 61

def convert number
  raise_on_type_mismatch number
  typed_conversion number
end

#of(number) ⇒ Integer Also known as: checksum

Calculates ISBN13 checksum

Examples:

Sjekksum::ISBN13.of("978-0-306-40615-") #=> 7

Parameters:

  • number (Integer, String)

    number for which the checksum should be calculated

Returns:

  • (Integer)

    calculated checksum


22
23
24
25
26
27
28
29
30
31
# File 'lib/sjekksum/isbn13.rb', line 22

def of number
  raise_on_type_mismatch number
  digits = convert_number_to_digits(number)

  sum    = digits.map.with_index do |digit, idx|
    idx.odd? ? (digit * 3) : digit
  end.reduce(&:+)

  (10 - sum % 10) % 10
end

#valid?(number) ⇒ Boolean Also known as: is_valid?

ISBN13 validation of provided number

Examples:

Sjekksum::ISBN13.valid?("978-0-306-40615-7") #=> true

Parameters:

  • number (Integer, String)

    number with included checksum

Returns:

  • (Boolean)

43
44
45
46
47
# File 'lib/sjekksum/isbn13.rb', line 43

def valid? number
  raise_on_type_mismatch number
  num, check = split_number(number)
  self.of(num) == check
end