Last active
December 21, 2015 23:18
-
-
Save ybur-yug/6380869 to your computer and use it in GitHub Desktop.
Phone number formatter. Takes a phone number in any format X, (rjowgij4195205bw300iofjs to 1(319)4920502, etc) and returns it in proper 1(xxx)-xxx-xxxx format. Epicodus exercise.
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
def phone_format(number) | |
phone_number = num_scrub(number) | |
real_number = phone_number.split("") | |
if real_number.length < 11 | |
num_sections = [["("],[],[]] | |
num_sections[0].push(real_number[0...3]) | |
num_sections[1] = real_number[3...6] | |
num_sections[2] = real_number[6..-1] | |
num_sections[0].push(")-") | |
num_sections[1].push("-") | |
area_code = num_sections[0].join("") | |
location_code = num_sections[1].join("") | |
end_digits = num_sections[2].join("") | |
puts area_code + location_code + end_digits | |
end | |
if real_number.length == 11 && real_number[0].to_s == "1" | |
num_sections = [[],["("],[],[]] | |
num_sections[0] = real_number[0] | |
num_sections[1].push(real_number[1...4]) | |
num_sections[2] = real_number[4...7] | |
num_sections[3] = real_number[7..-1] | |
num_sections[1].push(")-") | |
num_sections[2].push("-") | |
one = num_sections[0] | |
area_code = num_sections[1].join("") | |
location_code = num_sections[2].join("") | |
end_digits = num_sections[3].join("") | |
puts one + area_code + location_code + end_digits | |
end | |
else | |
puts "thats not a valid phone number in the US" | |
end | |
def num_scrub(str) | |
number = str | |
only_number = number.gsub(/[^\d]/, '') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment