Last active
August 29, 2015 14:10
-
-
Save wachunei/8bfe0e49b3d8e083e10d to your computer and use it in GitHub Desktop.
RUT Chile: obtener dígito verificador, validar y formatear
This file contains hidden or 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
def obtener_dv rut | |
rut = rut.to_s.tr(".-", "").reverse | |
suma = 0 | |
for index in 0..rut.size | |
suma+= rut[index].to_i * (2+index%6) | |
end | |
res = 11 - suma % 11 | |
res = (res == 11)? 0 : (res == 10)? "K" : res | |
res.to_s | |
end | |
def validar rut | |
rut.to_s.tr(".-", "")[-1] == (obtener_dv rut.to_s[0..-2]) | |
end | |
def formatear rut | |
rut = rut.to_s.tr(".-", "") | |
num = rut[0..-2] | |
dv = rut[-1] | |
num = num.to_s.reverse.gsub(/...(?=.)/,'\&.').reverse | |
"#{num}-#{dv}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment