Skip to content

Instantly share code, notes, and snippets.

@narath
Created September 16, 2012 01:29
Show Gist options
  • Save narath/3730694 to your computer and use it in GitHub Desktop.
Save narath/3730694 to your computer and use it in GitHub Desktop.
Pretty printing a phone number from a string
def pretty_phone_number(str_num)
# I know how to handle 9 digit numbers
# I know how to handle 10 digit numbers
# for above that I only know how to divide into 3s
result = ""
case
when str_num.length==10
result << '('+str_num[0..2]+') '+str_num[3..5]+'-'+str_num[6..9]
when str_num.length == 11 && str_num =~ /^1/
# assume north america and ignore the 1
result << '('+str_num[1..3]+') '+str_num[4..6]+'-'+str_num[7..10]
when str_num.length == 11 && str_num =~ /^[^1]/
result << '+'+str_num[0, 1]+' ('+str_num[1..3]+') '+str_num[4..6]+'-'+str_num[7..10]
else
str_num.chars.each_with_index do |c, i|
result << c
result << '-' if i%3==2 &&(i+3<str_num.length)
end
end
return result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment