0

I have a function that is parsing an array of numbers into a string in correct phone number format. Is there any way to condense this so that I only have to call .insert once?

createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) returns "(123) 456-7890")

def createPhoneNumber(numbers)
  numbers.insert(6, "-")
  numbers.insert(0, "(")
  numbers.insert(4, ")")
  numbers.insert(5, " ")
  numbers.join
end
1
  • This is something that'll break if you have international users, as phone number lengths and formats vary around the world. Also, method names are not camelCase, they're snake_case in Ruby so use create_phone_number. Commented Mar 5, 2014 at 6:00

2 Answers 2

3

If you don't mind passing in a 10-character string instead, you can do

def createPhoneNumber( p )
    '(%s) %s-%s' % [p[0,3],p[3,3],p[6,4]]    
end

Example:

createPhoneNumber('1234567890') # => "(123) 456-7890"
Sign up to request clarification or add additional context in comments.

1 Comment

Using a string is the right way to start. We see them in the "(xxx) xxx-xxxx" format in the US often, but elsewhere they'll vary. Even assuming they're ten digits is dangerous so the OP is painting their app into a US-centric corner.
2
def createPhoneNumber(numbers)
  "(#{numbers[0..2].join}) #{numbers[3..5].join}-#{numbers[6..9].join}"
end

There is no way I can think of where you would use insert, and use it only once.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.