Created
March 28, 2012 10:54
-
-
Save sunkencity/2225386 to your computer and use it in GitHub Desktop.
Validera personnummer
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
# encoding: utf-8 | |
class SocialSecurityNumber | |
def initialize str | |
if str =~ /(\d{2})(\d{2})(\d{2})(\d{4})/ | |
@str = str | |
@year,@month,@day,@last_four = $1,$2,$3,$4 | |
current_year = Time.now.year % 100 | |
century = @year.to_i > current_year ? "19" : "20" | |
@full_year = "#{century}#{@year}" | |
else | |
raise ArgumentError, "formatet är är felaktigt" | |
end | |
end | |
def valid_date? | |
begin | |
date = Time.new(@full_year.to_i,@month.to_i,@day.to_i,0,0) | |
rescue ArgumentError => e | |
return false | |
end | |
end | |
def valid_checksum? | |
checksum = Luhn.new(@str) | |
checksum.valid? | |
end | |
def valid? | |
valid_date? && valid_checksum? | |
end | |
class Luhn | |
def initialize str | |
@arr = str.split(//).map(&:to_i) | |
@sums = @arr.enum_for(:each_with_index).map do |x,index| | |
value = (index %2 == 0) ? x * 2 : x | |
((value < 10) ? value : value - 9) | |
end | |
end | |
def sum | |
@sums.inject { |a,b| a + b } | |
end | |
def valid? | |
sum % 10 == 0 | |
end | |
end | |
end | |
if __FILE__ == $0 | |
pnum=ARGV[0] | |
if pnum==nil then | |
print "Ange personnummer som yyMMddcccc.\n" | |
exit | |
end | |
ssn = SocialSecurityNumber.new pnum | |
puts ssn.valid? ? "Korrekt personnummer" : "Inkorrekt personnummer" | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment