Skip to content

Instantly share code, notes, and snippets.

@graemetait
Created July 26, 2012 13:00
Show Gist options
  • Save graemetait/3181908 to your computer and use it in GitHub Desktop.
Save graemetait/3181908 to your computer and use it in GitHub Desktop.
Ruby course - isbn 1
def check_isbn13(isbn)
total = 0
12.times do |i|
# puts i % 2
if i % 2 == 0
total += isbn[i].to_i
else
total += isbn[i].to_i * 3
end
end
checksum = 10 - (total % 10)
if (checksum == 10)
checksum = 0
end
valid = isbn.end_with? checksum.to_s
end
def strip_isbn(isbn)
isbn.gsub(/\-+/, "").gsub(/\s+/, "")
end
isbns = []
file = File.new("isbns", "r").each do |line|
line = strip_isbn line
valid = check_isbn13 line
print "#{line} "
puts valid ? 'valid' : 'not valid'
isbns.push line
end
# $ ruby isbn.rb
# 9780596516178 valid
# 9781430223634 valid
# 9780321584106 valid
# 9780321743121 valid
# 9781934356470 valid
# 9780321490452 valid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment