Ruby Algorithm — valid ISBN10

Another algorithm that I found online it’s a method to check if a string is a valid ISBN10 or not.

Firstly let’s find out what a valid ISBN 10 is.

ISBN is the acronym for International Standard Book Number. This 10 or 13-digit number (in our case 10) identifies a specific book, an edition of a book, or a book-like product (such as an audiobook). Since 1970 each published book has a unique ISBN. ( Find out more here: link)

ISBN-10 identifiers are ten digits long. The first nine characters are digits 0-9. The last digit can be 0-9 or X, to indicate a value of 10.

An ISBN-10 number is valid if the sum of the digits multiplied by their position modulo 11 equals zero.

I decided to work in Ruby this time, and now if we know what we need to create, let’s start by building some tests to validate our work.

I created some tests about the sum of the digits and also if the last digit is X to make sure and change it into a 10.

Now let’s get to solving it.

Before going into anything let’s return false if we receive as input a string with more than 10 digits.

return false if isbn.size != 10

Now let’s create to main variable total and output.

total = 0

output = true

We are going to use those later.

To check each digit I will iterate over then (converted into an array firstly) and do some checks. I will use each_with_index as we’re going to need the position of each digit.

The checks we need to do ar the following:

  • If the index of the number is equal to 9 (as it will be the last one) and is the digit is “X” to make the assignment to the number variable the value of 10.
  • If the digit is any other number to assign the output with a false value. Otherwise to add to the total variable the number, converted to an integer and multiplied by its index + 1.

Finally, we need to return the output variable and make sure the total modulo 11 equals zero.


What I learned from here is that Tests are very important. Without them, I didn’t check if the digit was an integer and 0%11=0. The method will return true if we pass as input 10 letters.

Full Stack Web Developer |