Skip to content

Instantly share code, notes, and snippets.

@roryokane
Created September 4, 2012 12:31
Show Gist options
  • Save roryokane/3620776 to your computer and use it in GitHub Desktop.
Save roryokane/3620776 to your computer and use it in GitHub Desktop.
editing Wikipedia ISBN calculation code
editing http://en.wikipedia.org/w/index.php?title=International_Standard_Book_Number, section “ISBN-13 check digit calculation”
page edits:
“/* ISBN-13 check digit calculation */ made Ruby checksum code more idiomatic (and easier-to-read)”
http://en.wikipedia.org/w/index.php?title=International_Standard_Book_Number&diff=prev&oldid=510791284
“ refactored Ruby code for clarity”
http://en.wikipedia.org/w/index.php?title=International_Standard_Book_Number&diff=510791920&oldid=510791284
# helper methods not worth the space for the Wikipedia example
def String.split_into_chars
self.split(//)
end
def Numeric.divisible_by(num)
self.modulo(num).zero?
end
def Enumerable.sum #implemented in Rails ActiveSupport
self.reduce(:+)
end
# idiomatic
# Ruby
def isbn_checksum(isbn_string)
digits = isbn_string.split(//).map(&:to_i)
transformed_digits = digits.each_with_index.map do |digit, digit_index|
digit_index.modulo(2).zero? ? digit : digit*3
end
sum = transformed_digits.reduce(:+)
end
def is_valid_isbn13?(isbn13)
checksum = isbn_checksum(isbn13)
checksum.modulo(10).zero?
end
def isbn13_checksum_digit(isbn12)
checksum = isbn_checksum(isbn12)
10 - checksum.modulo(10)
end
# original
# Ruby
def is_valid_isbn13?(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 isbn13_checksum(isbn12)
sum = 0
12.times { |i| sum += i.modulo(2)==0 ? isbn12[i].to_i : isbn12[i].to_i*3 }
10 - sum.modulo(10)
end
require 'test/unit'
# require './original'
require './idiomatic'
class TestIsbn < Test::Unit::TestCase
def test_verifies_isbn13s
assert is_valid_isbn13?("9780306406157")
assert ! is_valid_isbn13?("1234567890123")
end
def test_calculates_isbn12_checksums
assert_equal 7, isbn13_checksum_digit("978030640615")
assert_equal 8, isbn13_checksum_digit("123456789012")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment