Skip to content

Instantly share code, notes, and snippets.

@davidbella
Created September 27, 2013 13:40
Show Gist options
  • Save davidbella/6728732 to your computer and use it in GitHub Desktop.
Save davidbella/6728732 to your computer and use it in GitHub Desktop.
Ruby: Formatting phone numbers (naive)
# Download this file:
# https://gist.github.com/scottcreynolds/ac1b5c8d96de0c91bf7c/download
# Run it from your terminal with:
# ruby ruby_phone_format.rb
# (Just make sure you are in the right directory)
# ======================================
# Ignore All This Code
# ======================================
@tests = 0
def test(title, &b)
@tests += 1
begin
if b
result = b.call
if result.is_a?(Array)
puts "#{@tests}. fail: #{title}"
puts " expected #{result.first} to equal #{result.last}"
elsif result
puts "#{@tests}. pass: #{title}"
else
puts "#{@tests}. fail: #{title}"
end
else
puts "#{@tests}. pending: #{title}"
end
rescue => e
puts "fail: #{title}"
puts e
end
end
def assert(statement)
!!statement
end
def assert_equal(actual, expected)
if expected == actual
true
else
[expected, actual]
end
end
class Object
def __
puts "__ should be replaced with a value or expression to make the test pass."
false
end
end
# ======================================
# Start Here - Make these tests pass.
# ======================================
# Define a method named normalize_phone_number that takes one
# string argument and returns a string in the format
# (XXX) XXX-XXXX if possible, and just returns the input string if not
# Method definition goes here:
def normalize_phone_number(number)
numbers = []
number.each_char do |char|
if "0123456789".include?(char)
numbers << char
end
end
if numbers.length < 10
number
else
"(" + numbers[0,3].join + ") " + numbers[3,3].join + "-" + numbers[6,4].join
end
end
def normalize_phone_number(number)
numbers = number.scan(/\d/)
if numbers.length < 10
number
else
sprintf "(%3s) %3s-%4s", numbers[0,3].join, numbers[3,3].join, numbers[6,4].join
end
end
# 1.
test 'that "1234567890" gets formatted' do
assert_equal normalize_phone_number("1234567890"), "(123) 456-7890"
end
# 2.
test 'that "(123)4567890" gets formatted' do
assert_equal normalize_phone_number("(123)4567890"), "(123) 456-7890"
end
# 3.
test 'that "123 456 7890" gets formatted' do
assert_equal normalize_phone_number("123 456 7890"), "(123) 456-7890"
end
# 4.
test 'that "123-4567890" gets formatted' do
assert_equal normalize_phone_number("123-4567890"), "(123) 456-7890"
end
# 5.
test 'that "123-456-7890" gets formatted' do
assert_equal normalize_phone_number("123-456-7890"), "(123) 456-7890"
end
# 6.
test 'that "123ABF90" does not get formatted' do
assert_equal normalize_phone_number("123ABF90"), "123ABF90"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment