I have a program that will format a phone number in this format: (###)###-####
def obtain_phone_number
loop do
print 'Enter phone number: '
phone_num = gets.chomp
if !(phone_num[/\d{10}/])
puts 'Invalid phone number, must contain 10 digits only'
else
formatted_phone_num = phone_num.insert(0, '(').insert(4, ')').insert(8, '-')
return formatted_phone_num
end
end
end
When run:
irb(main):013:0> obtain_phone_number Enter phone number: 1234567894 => "(123)456-7894" irb(main):014:0> obtain_phone_number Enter phone number: 7894561234 => "(789)456-1234" irb(main):015:0> obtain_phone_number Enter phone number: 5555555555 => "(555)555-5555"
This works and all, and is great, but are there better ways to format a phone number? Something that's not as ugly as phone_num.insert(0, '(').insert(4, ')').insert(8, '-')
. This just seems like it could be done in a more simplistic and easier way, and not to mention it will allow more than 10 digits.