Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Marcello Nuccio

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

validates italian CF

This function validates italian CF (fiscal code) by:
- checking for valid characters
- verifying checksum

def valid_cf?(cf)
  def ascii_displacement(ch)
   (?0..?9) === ch[0] ? (ch[0] - ?0) : (ch[0] - ?A)
  end

  return false if cf !~ %r{^[a-z]{6}\d{2}[abcdehlmprst]\d{2}[a-z]\d{3}[a-z]$}i
  sum = 0
  cf[0..-2].upcase.scan(/(.)(.)?/) do |a, b|
    sum += [ 1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 2, 4, 18, 20,
            11, 3, 6, 8, 12, 14, 16, 10, 22, 25, 24, 23
           ][ascii_displacement(a)]
    sum += ascii_displacement(b) unless b.nil?
  end
  (sum % 26 + ?A) == cf[-1,1].upcase[0]
end
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS