Top Level Namespace

Instance Method Summary collapse

Instance Method Details

#clean(isbn) ⇒ Object

This helper method just cleans up ISBNs



40
41
42
# File 'lib/isbn-converter.rb', line 40

def clean(isbn)
	isbn.gsub(/[^0-9X]/,'')
end

#to10(isbn) ⇒ Object

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”)



28
29
30
31
32
33
34
35
36
37
# File 'lib/isbn-converter.rb', line 28

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

#to13(isbn) ⇒ Object

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”)



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/isbn-converter.rb', line 5

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