Created
May 5, 2013 18:21
-
-
Save codesliced/5521665 to your computer and use it in GitHub Desktop.
My solutions for DBC prep exercise using regular expressions
This file contains 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
# Determine whether a string contains a Social Security number. | |
def has_ssn?(string) | |
%r{\d{3}\-\d{2}-\d{4}} =~ string | |
end | |
# Return the Social Security number from a string. | |
def grab_ssn(string) | |
string.slice(/\d{3}\-\d{2}\-\d{4}/) | |
end | |
# Return all of the Social Security numbers from a string. | |
def grab_all_ssns(string) | |
string.scan(/\d{3}\-\d{2}\-\d{4}/) | |
end | |
# Obfuscate all of the Social Security numbers in a string. Example: XXX-XX-4430. | |
# use sub or gsub -- gsub changes all of the occurrences | |
def hide_all_ssns(string) | |
string.gsub(/\d{3}\-\d{2}\-/, "XXX-XX-") | |
end | |
# Ensure all of the Social Security numbers use dashes for delimiters. | |
# Example: 480.01.4430 and 480014430 would both be 480-01-4430. | |
def format_ssns(string) | |
if string.match(/\b\d{9}\b/) | |
string.insert(5, '-') # start inserting from the rightmost side | |
string.insert(3, '-') | |
string.gsub(/\b\D\b/) { |m| '-' } | |
else | |
return string | |
end | |
end | |
puts has_ssn?("444-33-4327") | |
puts grab_ssn("please confirm your identity: 542-54-1422") | |
puts grab_all_ssns("554-43-9871 : 212-54-1422") | |
puts hide_all_ssns("554-43-9871 : 212-54-1422") | |
puts format_ssns("234601422, 350.80.0744, 013-60-8762") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment