Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def validate_isbn(isbn)
- return true if isbn.nil?
- digits = isbn.gsub(/[^0-9X]/, '').split(//).map { |d| d == "X" ? 10 : d.to_i }
- if digits.length == 10
- # ISBN-10
- partial = total = 0
- digits.each do |d|
- partial += d
- total += partial
- end
- return total.modulo(11) == 0
- elsif digits.length == 13
- # ISBN-13
- sum = 0
- digits[0..11].each_with_index do |d, i|
- sum += d * (i.odd? ? 3 : 1)
- end
- sum = sum % 10
- return digits[12] == (10 - sum)
- else
- return false
- end
- end
Add Comment
Please, Sign In to add comment