Skip to content

Instantly share code, notes, and snippets.

@Drowze
Created November 3, 2016 18:23
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 Drowze/a62f107b8806a05701c67ae439eea0fa to your computer and use it in GitHub Desktop.
Save Drowze/a62f107b8806a05701c67ae439eea0fa to your computer and use it in GitHub Desktop.
simple method to check a cpf
def check_cpf(cpf=nil)
return false if cpf.nil?
known_invalid_cpfs = %w{12345678909 11111111111 22222222222 33333333333
44444444444 55555555555 66666666666 77777777777
88888888888 99999999999 00000000000 }
cpf_digits = cpf.scan /[0-9]/
if cpf_digits.length == 11
unless known_invalid_cpfs.include?(cpf_digits.join)
cpf_digits = cpf_digits.map{|x| x.to_i}
sum = 0
(0..8).each { |n| sum += (10-n) * cpf_digits[n] }
sum = sum - (11 * (sum/11))
expected_tenth_digit = (sum == 0 || sum == 1) ? 0 : 11 - sum
if expected_tenth_digit == cpf_digits[-2] # is the 10th digit valid?
sum = 0
(0..9).each { |n| sum += cpf_digits[n] * (11-n) }
sum = sum - (11 * (sum/11))
expected_eleventh_digit = (sum == 0 || sum == 1) ? 0 : 11 - sum
return true if expected_eleventh_digit == cpf_digits[-1] # is the last digit valid?
end
end
end
return false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment