Skip to content

Instantly share code, notes, and snippets.

@markmcspadden
Created December 17, 2010 05:47
Show Gist options
  • Save markmcspadden/744539 to your computer and use it in GitHub Desktop.
Save markmcspadden/744539 to your computer and use it in GitHub Desktop.
Add hyphens in the right places for phone numbers...simulates real time input
require 'test/unit'
class PhoneNumberizeTest < Test::Unit::TestCase
# MM2: The one liner....and the one called by the tests
# yes it's ugly...I would probably not like to pick up someone else's code and see this ;)
def phone_numberize(number)
number.gsub(/#{/(\d{#{number.length-10}})/ if number.length>10}(\d{3})(\d{3})?(\d{1,4})/,"\\1-\\2-\\3-\\4").gsub("--","-").chomp("-")
end
# MM2: A long drawn out version...especially with the international twist...but it's more readable
# Not called by tests. Change the method name to test it.
def phone_numberize2(number)
number_string = "#{number}"
if number.length > 10
international = /\d{#{number.length-10}}/
really_long_match = number.match(/(#{international})(\d{3})(\d{3})(.+)/)
if really_long_match
number_string = "#{$1}-#{$2}-#{$3}-#{$4}"
end
elsif number.length > 6
long_match = number.match(/(\d{3})(\d{3})(.+)/)
if long_match
number_string = "#{$1}-#{$2}-#{$3}"
end
elsif number.length > 3
short_match = number.match(/(\d{3})(.+)/)
if short_match
number_string = "#{$1}-#{$2}"
end
end
number_string
end
def test_one_number
assert_equal "4", phone_numberize("4")
end
def test_two_numbers
assert_equal "46", phone_numberize("46")
end
def test_three_numbers
assert_equal "469", phone_numberize("469")
end
def test_four_numbers
assert_equal "469-2", phone_numberize("4692")
end
def test_five_numbers
assert_equal "469-23", phone_numberize("46923")
end
def test_six_numbers
assert_equal "469-236", phone_numberize("469236")
end
def test_seven_numbers
assert_equal "469-236-9", phone_numberize("4692369")
end
def test_eight_numbers
assert_equal "469-236-94", phone_numberize("46923694")
end
def test_nine_numbers
assert_equal "469-236-948", phone_numberize("469236948")
end
def test_ten_numbers
assert_equal "469-236-9488", phone_numberize("4692369488")
end
def test_eleven_numbers
assert_equal "1-469-236-9488", phone_numberize("14692369488")
end
def test_twelve_numbers
assert_equal "01-469-236-9488", phone_numberize("014692369488")
end
def test_thirteen_numbers
assert_equal "001-469-236-9488", phone_numberize("0014692369488")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment