# 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