Skip to content

Instantly share code, notes, and snippets.

@ciprianna
Last active August 29, 2015 14:22
Show Gist options
  • Save ciprianna/7189a9e8b261b2b5eeb7 to your computer and use it in GitHub Desktop.
Save ciprianna/7189a9e8b261b2b5eeb7 to your computer and use it in GitHub Desktop.
Mini Projects - Phone Number Formatter
# app.rb
require "./phone_number_formatter.rb"
puts "What's your phone number?"
number_input = gets.chomp
test = PhoneNumber.new(number_input)
puts "That's #{test.number}, right?"
# Phone Number Formatter
class PhoneNumber
attr_accessor :number
# When the object is initialized, it takes one argument.
#
# number_input - string
#
# Runs the format_number method using the number_input as the argument
def initialize(number_input)
format_number(number_input)
end
# Changes the input to the correct format.
#
# Uses the substitution method to manipulate the number_input. Finds a pattern
# using regex. Pattern looks for a group of three digits, then a group of
# three digits, then a group of four digits. It then substitutes that
# pattern with parentheses, inside the parentheses it puts the regex group 1
# followed by a space character, then regex group 2, then a dash, and then
# the regex group three pattern.
#
# Returns and stores the result as an instance variable.
def format_number(number_input)
@number = number_input.sub(/(\d{3})(\d{3})(\d{4})/,'(\1) \2-\3')
end
end
# Phone Number Formatter Test
require "minitest/autorun"
require_relative "phone_number_formatter.rb"
class PhoneNumberFormatterTest < Minitest::Test
# Need to test the format number method to ensure the inputted String returns
# a properly formatted String to look like a phone number.
def test_phone_number_formatter
number = PhoneNumber.new("1234567890")
assert_equal("(123) 456-7890", number.format_number("1234567890"))
end
end
@ciprianna
Copy link
Author

Thanks. That was a giant waste of most of my afternoon yesterday, so I was glad when I finally got it working!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment