phone_number.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class PhoneNumber
  def initialize(num)
    @parts = parse_number(num)
  end

  def to_s
    "(%s) %s-%s" % @parts
  end

  def area_code
    @parts[0]
  end

  def number
    @parts.join('')
  end

private
  def parse_number(num)
    clean = num.gsub(/[^\w]+/, '')
    clean =~ /^1?(\d{3})(\d{3})(\d{4})$/ ?  [$1, $2, $3] : @@invalid_number
  end

  @@invalid_number = ['000', '000', '0000']
end

Comments


You're not logged in right now. Please login via GitHub to comment