Skip to content

Instantly share code, notes, and snippets.

@otaviocorrea
Last active December 5, 2022 22:44
Show Gist options
  • Save otaviocorrea/1285e8c2f8ee3870da63cef8f0be9627 to your computer and use it in GitHub Desktop.
Save otaviocorrea/1285e8c2f8ee3870da63cef8f0be9627 to your computer and use it in GitHub Desktop.
Código Ruby para validação do CNS (Cartão Nacional de Saúde)
def valid_cns?(cns) # CNS is a String
return false unless (cns.match('[1-2]\\d{10}00[0-1]\\d') || cns.match('[7-9]\\d{14}'))
return weighted_sum(cns) % 11 == 0;
end
def weighted_sum(cns)
total = 0
cns.chars.each_with_index { |char, index| total += (char.to_i * (15 - index)) }
total
end
# REFs:
# https://integracao.esusab.ufsc.br/ledi/documentacao/regras/algoritmo_CNS.html
# https://gist.github.com/yanaga/3024877
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment