Skip to content

Instantly share code, notes, and snippets.

@mudge
Last active March 16, 2016 16:37
Show Gist options
  • Save mudge/48af8f81392c592bb801 to your computer and use it in GitHub Desktop.
Save mudge/48af8f81392c592bb801 to your computer and use it in GitHub Desktop.
Extract 13-digit ISBNs from some input text
# isbns('978-0-80-506909-9 9780671879198 0-415-82102-9 3319217283')
# => ["9780805069099", "9780671879198", "9789780805067", "9789780671877", "9780415821025", "9783319217284"]
def isbns(text)
thirteen_digit_isbns(text) + ten_digit_isbns(text)
end
def thirteen_digit_isbns(text)
text.tr('-', '').scan(/\b97[89]\d{10}\b/)
end
def ten_digit_isbns(text)
text.tr('-', '').scan(/\b\d{10}\b/).map { |isbn|
isbn.chop!
isbn.prepend('978')
check_digit = 10 - isbn.each_char.zip([1, 3].cycle).inject(0) { |acc, (digit, weight)| acc + (Integer(digit) * weight) } % 10
isbn << check_digit.to_s
isbn
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment