Skip to content

Instantly share code, notes, and snippets.

@branch14
Created June 9, 2013 19:18
Show Gist options
  • Save branch14/5744802 to your computer and use it in GitHub Desktop.
Save branch14/5744802 to your computer and use it in GitHub Desktop.
script to convert isbn13 to isbn10
#!/usr/bin/env ruby
# returns isbn10 if the given string represents a isbn13
# returns the given string otherwise
def isbn13to10(line)
isbn13 = line.tr_s('- ', '')
return line unless isbn13.match(/\d{13}/)
isbn10 = isbn13[3,9]
checksum = 0
isbn10.split('').each_with_index do |c, i|
checksum += c.to_i * (10 - i)
end
checksum = 11 - (checksum % 11)
checksum = 'X' if checksum == 10
checksum = '0' if checksum == 11
isbn10 + checksum.to_s
end
content = File.read(ARGV[0])
puts *content.split("\n").map { |line| isbn13to10(line) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment