/phone-number-with-letters

Lib converts phone numbers like 1-800-PRINT-ME into 1-800-77468-63

Primary LanguageRuby

Phone Number With Letters Converter

Lib converts phone numbers like 1-800-PRINT-ME into 1-800-77468-63

Translation

PhoneNumberWithLetters::translate translates phone number with letters into digit number

require 'phone_number_with_letters'

PhoneNumberWithLetters.translate("1-800-PRINT-ME") # => "1-800-77468-63"
PhoneNumberWithLetters.translate("1-800-FLOWERS")  # => "1-800-3569377"
PhoneNumberWithLetters.translate("1-800-APL-CARE") # => "1-800-275-2273"

And takes into account phone number extension and DOES NOT translate it into digits

PhoneNumberWithLetters.translate("1-800-275-2273")          # => "1-800-275-2273"
PhoneNumberWithLetters.translate("1.800.275.2273 x.1234")   # => "1.800.275.2273 x.1234"
PhoneNumberWithLetters.translate("1-800-275-2273 ext1234")  # => "1-800-275-2273 ext1234"

Converting

Usually phone number (in USA) contains 11 characters (digits), but phone number with letters can contain more then 11 characters to be more rememberable. For example

  • "1-877-4-APL-PROMO" (13 chars) corresponds to "1-877-4-275-776" (11 digits)
  • "1-800-MY-IPHONE" (12 chars) corresponds to "1-800-69-47466" (11 digits)
  • "1.877.KARS.4.KIDS." (13 chars) corresponds to "1-877-5277-4-54" (11 digits)

Simple translating "1-877-4-APL-PROMO" gives us 13 characters "1-877-4-275-77666" with 2 extra digits But real phone number should be "1-877-4-275-776". For this purpose PhoneNumberWithLetters provides method ::convert witch cuts off extra characters

# translate does nothing with extra digits
PhoneNumberWithLetters.translate("1-877-4-APL-PROMO") # => "1-877-4-275-77666"

# convert cuts off extra digits
PhoneNumberWithLetters.convert("1-877-4-APL-PROMO") # => "1-877-4-275-776"

And like ::translate doesn't cut off extension numbers

# a very strange phone number
PhoneNumberWithLetters.convert("1.877.KARS.4.KIDS. ext1234") # => "1.877.5277.4.54 ext1234",

You can specify how much characters phone number should contain by passing second argument. Default is 11.

PhoneNumberWithLetters.convert("1.877.KARS.4.KIDS.", 13) # => "1-877-5277-4-5437"
PhoneNumberWithLetters.convert("1.877.KARS.4.KIDS.", 8)  # => "1-877-5277"

Copiright

Copyright © 2009 Pavel Gorbokon, released under the MIT license