Created
April 26, 2012 13:08
-
-
Save matheustardivo/2499428 to your computer and use it in GitHub Desktop.
Validador de CPF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ValidadorCPF | |
REGEX = /\A(\d{3}\.?){2}\d{3}\-?\d{2}\Z/ | |
def self.valido?(cpf) | |
return false unless REGEX =~ cpf | |
arr = cpf.scan(/\d/).take(9) | |
arr << calcular_dv(arr) | |
arr << calcular_dv(arr) | |
cpf.scan(/\d/).join == arr.join | |
end | |
def self.calcular_dv(arr) | |
arr2 = arr.reverse.each_with_index.map { |item, index| (index + 2) * item.to_i } | |
val = arr2.reduce(:+) | |
mod = val % 11 | |
if mod < 2 | |
0 | |
else | |
11 - mod | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment