Skip to content

Instantly share code, notes, and snippets.

@Haumer
Created July 19, 2021 17:05
Show Gist options
  • Save Haumer/9f06aa6c20d5b7da403b920791e880f5 to your computer and use it in GitHub Desktop.
Save Haumer/9f06aa6c20d5b7da403b920791e880f5 to your computer and use it in GitHub Desktop.
require 'date'
require 'yaml'
# 1) define a method #french_ssn_info
def french_ssn_info(ssn_number)
# 2) write regex to match
# gender (first digit) => 1 male 2 female
# year (next 2 digits)
# month (next 2 digits)
# department (next 2 digits)
# random 6 digits
# last two digits for check
match_data = ssn_number.match(/(?<gender>[12])\s?(?<year>\d{2})\s?(?<month>0[1-9]|1[0-2])\s?(?<dept>0[1-9]|[1-9]\d)\s?(?<random>\d{3}\s?\d{3})\s?(?<key>\d{2})/)
# 3) check if ssn is valid ((97 - ssn) % 97) == last 2 digits
# key = match_data[:key].to_i
# subtract = ssn_number[0..-3].gsub(/\s/, "").to_i
# ssn_valid?(ssn_number[0..-3].gsub(/\s/, "").to_i,match_data[:key].to_i)
# 4) print out a nice string
if ssn_valid?(ssn_number[0..-3].gsub(/\s/, "").to_i,match_data[:key].to_i)
# "a man, born in December, 1984 in Seine-Maritime."
"a #{gender(match_data[:gender])}, born in #{monthname(match_data[:month])}, #{year(match_data[:year])} in #{department(match_data[:dept])}"
else
# 5) notify user if invalid
return "The number is invalid"
end
end
def ssn_valid?(ssn_without_key, key)
(97 - ssn_without_key) % 97 == key
end
def gender(code)
code.to_i == 1 ? "man" : "woman"
end
def year(code)
"19#{code}"
end
def monthname(code)
Date::MONTHNAMES[code.to_i]
end
def department(code)
YAML.load_file("data/french_departments.yml")[code]
end
p french_ssn_info("1 84 12 76 451 089 46")
# p french_ssn_info("1 84")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment