Module: Sjekksum::ISBN10

Extended by:
ISBN10, Shared
Included in:
ISBN10
Defined in:
lib/sjekksum/isbn10.rb

Overview

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

Instance Method Summary collapse

Instance Method Details

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

Transforms a number by appending the ISBN-10 checksum digit

Examples:

Sjekksum::ISBN10.convert("147743025") #=> "1477430253"
Sjekksum::ISBN10.convert("193435600") #=> "193435600X"

Parameters:

  • number (Integer, String)

    number without a checksum

Returns:

  • (Integer, String)

    final number including the checksum


61
62
63
64
65
66
67
68
69
# File 'lib/sjekksum/isbn10.rb', line 61

def convert number
  raise_on_type_mismatch number
  check = self.of(number)
  if number.is_a?(String) or check.is_a?(String)
    number.to_s << self.of(number).to_s
  else
    convert_to_int(number) * 10 + self.of(number)
  end
end

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

Calculates ISBN-10 checksum

Examples:

Sjekksum::ISBN10.of("147743025") #=> 3
Sjekksum::ISBN10.of("193435600") #=> "X"

Parameters:

  • number (Integer, String)

    number for which the checksum should be calculated

Returns:

  • (Integer, String)

    calculated checksum


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

def of number
  raise_on_type_mismatch number
  digits = convert_number_to_digits(number)[0..9]

  sum    = digits.reverse_each.with_index.reduce(0) do |check, (digit, idx)|
    check += digit * (idx+2)
  end

  check = (11 - sum % 11) % 11
  check == 10 ? "X" : check
end

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

ISBN-10 validation of provided number

Examples:

Sjekksum::ISBN10.valid?("1477430253") #=> true
Sjekksum::ISBN10.valid?("193435600X") #=> true

Parameters:

  • number (Integer, String)

    number with included checksum

Returns:

  • (Boolean)

44
45
46
47
48
# File 'lib/sjekksum/isbn10.rb', line 44

def valid? number
  raise_on_type_mismatch number
  num, check = split_isbn_number(number)
  convert_number_to_digits(num).length == 9 && self.of(num) == check
end