YoYoYo I'm Awesome YoYoYo I'm Awesome - 3 months ago 10
Ruby Question

Add the '-' in the phone number, along with the ext

I need a way to add the '-' into a phone number, verify that it is the correct length, add parenthesis around the area code, and default to nil if no extension is given. For example:

9876542123 ext: 6789 -> Should end up -> (987)654-2123 ext: 6789
4543456 -> should fail
9876785678 ext: -> should end up -> (987)678-5678


How can I do this without a regular expression?

What I've attempted:

def format_phone_number(num)
num.insert(0, '(').insert(-3, ')').insert(-4, '-')
end


Outputs:

(12345678-)94

Answer

You have to deal with the side-effect that you are changing the size of the string on each call to insert:

def format_phone_number(num)
  num.insert(0, '(')
  puts num                       #=> (9876785678
  puts num.size                  #=> 11
  num.insert(4, ')')
  puts num                       #=> (987)6785678
  puts num.size                  #=> 12
  num.insert(8, '-')
  puts num                       #=> (987)678-5678 
  puts num.size                  #=> 13 
end

format_phone_number("9876785678")
Comments