Sha256: 6a9e281d4270116464a311359529d247efa604f593a4f05003540bd98406e1e6

Contents?: true

Size: 738 Bytes

Versions: 1

Compression:

Stored size: 738 Bytes

Contents

require "petrarca/helpers"


module Petrarca
  module ISBN10

    include Helpers

    extend self

    def valid?(isbn)
      correct_format?(isbn) && isbn[-1] == calc_check_digit(isbn)
    end

    def correct_format?(isbn)
      isbn = isbn.delete("-")
      !!(/\A\d{9}[0-9X]\z/ =~ isbn)
    end

    def calc_check_digit(isbn)
      nums = isbn.delete("-").split("")[0..8].map{|x| x.to_i }
      sum = nums.zip((2..10).to_a.reverse).map{|x, y| x * y }.inject(:+)
      check_digit = 11 - (sum % 11)
      case check_digit
      when 10
        "X"
      when 11
        "0"
      else
        check_digit.to_s
      end
    end

    def hyphenate(isbn)
      s = hyphenate13("978" + isbn)
      s.sub(/^978-/, "")
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
petrarca-0.2.0 lib/petrarca/isbn10.rb