Last active
December 10, 2015 16:18
-
-
Save gongo/4459812 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class String | |
# | |
# Convert ISBN-10 to ISBN-13 | |
# | |
# http://www.infonet.co.jp/ueyama/ip/glossary/isbn.html | |
# http://en.wikipedia.org/wiki/Check_digit#ISBN_13 | |
# | |
# @return [String] String as ISBN-13 format | |
# | |
def toISBN13 | |
raise TypeError.new 'must be 10 digit chars in length' unless self.ISBN10? | |
base = [9,7,8] + self[0...-1].split(//).map(&:to_i) | |
check_digit = 10 - base.zip([1,3]*6).inject(0) { |s, v| s += v[0] * v[1] } % 10 | |
check_digit = 0 if check_digit === 10 | |
return base.join + check_digit.to_s | |
end | |
def ISBN10? | |
return /^\d{9}(\d|X)$/ =~ self | |
end | |
end | |
# http://www.amazon.co.jp/dp/4048687158/ | |
p "4048687158".toISBN13 # => "9784048687157" | |
# http://www.amazon.co.jp/dp/4873113946/ | |
p "4873113946".toISBN13 # => "9784873113944" | |
# not 10 digit chars | |
p "12345".toISBN13 # => raise TypeError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment