match[0].split(/[- ]?/).each_with_index do |x, i|
# warning `i’ will take the values 0 … 9
end
Merci bien. Not only does this remove the need of a lengthy pattern,
it also allows for a more readable implementation. I post it because
IIRC some people have shown interest in validating ISBNs.
def validate_isbn!
match = /(\d[- ]?){9,9}([0-9xX])/.match(@isbn)
if match == nil
return ‘ISBN pattern mismatch’
end @isbn = ‘’
checksum = 0
match[0].split(/[- ]?/).each_with_index { |char, index|
case char
when ‘X’, ‘x’
checksum += 10 @isbn += ‘X’
else
checksum += (10 - index) * char.to_i @isbn += char
end
}
(checksum.remainder(11) == 0 ? ‘’ : ‘in’) + ‘valid checksum’
end