I was using phony to format phone numbers (meaning, if I put in xxx-xxx-xxxx it would convert to a string, and also tell if there is a (1) before to remove it).
But
I've never seen much in the way of a reliable telephone number formatter because it's just so hard to get it right. Just when you think you've seen everything, some other format comes along and wrecks it.
Ten digit North American numbers are perhaps the easiest to format, you can use a regular expression, but as soon as you encounter extensions you're in trouble. Still, you can kind of hack it yourself if you want:
def formatted_number(number)
digits = number.gsub(/\D/, '').split(//)
if (digits.length == 11 and digits[0] == '1')
# Strip leading 1
digits.shift
end
if (digits.length == 10)
# Rejoin for latest Ruby, remove next line if old Ruby
digits = digits.join
'(%s) %s-%s' % [ digits[0,3], digits[3,3], digits[6,4] ]
end
end
This will just wrangle eleven and ten digit numbers into the format you want.
Some examples:
formatted_number("1 (703) 451-5115")
# => "(703) 451-5115"
formatted_number("555-555-1212")
# => "(555) 555-1212"