Sha256: 0f6248a8b1bf6ac1e56bb34909986ac8507260f1b797797813a84e89a59ae251
Contents?: true
Size: 1.21 KB
Versions: 1
Compression:
Stored size: 1.21 KB
Contents
# Convert ISBN as 10-digit string to 13-digit string # Can handle dashes, returns nil if the ISBN is not 10 digits # Also returns the ISBN if ISBN is 13 digits and begins with 978 or 979 # Por ejemplo: to13("0940016737") def to13(isbn) isbn = clean(isbn) if isbn.length == 13 && ["978","979"].member?(isbn[0..2]) return isbn elsif isbn.length != 10 return nil end new_isbn = "978" + isbn.chop check = 0 new_isbn.split(//).each_with_index do |digit, index| if index % 2 == 0 check += digit.to_i * 1 else check += digit.to_i * 3 end end check = if check % 10 == 0 then 0 else 10 - (check % 10) end new_isbn + check.to_s end # Convert ISBN as 13-digit string to 10-digit string # Can handle dashes, returns nil if the ISBN is not 13 digits # Por ejemplo: to10("978-0-940016-73-6") def to10(isbn) isbn = clean(isbn) return nil unless isbn.length == 13 && isbn[0..2] != "979" new_isbn = isbn.chop[3..(isbn.length - 1)] check = 0 10.downto(2) { |n| check += new_isbn[(10 - n)..(10 - n)].to_i * n } check = 11 - (check % 11) check = "X" if check == 10 new_isbn + check.to_s end # This helper method just cleans up ISBNs def clean(isbn) isbn.gsub(/[^0-9X]/,'') end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
isbn-converter-0.1.0 | lib/isbn-converter.rb |