Question: 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")

```

To handle phone numbers of less than 10 characters, you could `raise` an exception:

```
def format_phone_number(num)
  raise "Less than 10 chars" if num.size < 10
  num.insert(0, '(').insert(4, ')').insert(8, '-')
end

format_phone_number "9876785678"            #=> (987)654-2123   
format_phone_number "9876542123 ext: 6789"  #=> (987)654-2123 ext: 6789
format_phone_number "9876542123 ext:"       #=> (987)654-2123 ext: 
format_phone_number "987678567"             #=> in `format_phone_number': Less than 10 chars (RuntimeError) 

```
The following should closely resemble what you're looking for. When you insert a character into a string then you have to remember that you're increasing the length of the string by 1. Also, using a negative index with insert, inserts the character at position `num.length - index`.

```
def format_phone_number(num)
  if num.length >= 10
    num.insert(0, '(').insert(4, ')').insert(8, '-')
  end
end

```

I'm not sure what you want to return if the phone number is not the appropriate length.