Skip to content

Instantly share code, notes, and snippets.

@matheustardivo
Created April 26, 2012 13:08
Show Gist options
  • Save matheustardivo/2499428 to your computer and use it in GitHub Desktop.
Save matheustardivo/2499428 to your computer and use it in GitHub Desktop.
Validador de CPF
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