Skip to content

Instantly share code, notes, and snippets.

@pootsbook
Created July 26, 2012 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pootsbook/3181925 to your computer and use it in GitHub Desktop.
Save pootsbook/3181925 to your computer and use it in GitHub Desktop.
Solutions to ISBN cleaning and validation
Paste solutions in the comments below. Don't forget to make it code using GitHub markdown.
@anthonysterling
Copy link

@byrichardpowell
Copy link

@MikeHibbert
Copy link

@jamesmills
Copy link

@jamiefdhurst
Copy link

@utterlyforked
Copy link

#!/usr/bin/env ruby

def is_isbn13_checksum_valid?(isbn13)
  sum = 0
  13.times { |i| sum += i.modulo(2)==0 ? isbn13[i].to_i : isbn13[i].to_i*3 }
  0 == sum.modulo(10)
end

def is_isbn_length_valid?(isbn)
  return isbn.length == 13
end

File.open("isbn.txt", "r").each_line { |s|
  isbn = s.scan(/\d/).join('')
  if is_isbn_length_valid?(isbn) && is_isbn13_checksum_valid?(isbn)
    puts isbn + ' is valid'
  else
    puts isbn + ' is not valid'
  end
}

@samlambert
Copy link

@creativenucleus
Copy link

@graemetait
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment