Codes316 Codes316 - 1 month ago 7
Ruby Question

How to make a program that allows the user to label what type of input is provided?

I have a program in Ruby that takes a phone number and is able to pull information from that number. It can tell me the area code, the root, and prefix of the number.

I now want to add another parameter where the user can input that this particular phone number is their cell, work number, etc.

For example:

MyContact1 = Info.new ('(555) 555-5555', :home)
=>(555) 555-5555 (home)

MyContact1.label
=>"home"

MyContact2. = Info.new (' 555-555-5555, "work")
=>(555) 555-5555 (work)


Here is my code:

class PhoneNumber

def initialize (ph)
@ph = ph
@ph.insert(0, '(')
@ph.insert(4, ')')
@ph.insert(5, ' ')
@ph.insert(9, "-")
end
def to_s
@ph
end
def area_code
@ph.slice(0..5)
end
def prefix
@ph.slice(6..8)
end
def root
@ph.slice(10..13)
end
end
print "Please enter a phone number: "
puts a = PhoneNumber.new(gets.strip)
puts a.area_code
puts a.prefix
puts a.root

Answer

Just extend your initialize method to accept more arguments:

class PhoneNumber

  attr_reader :label

  def initialize(ph, label)
    @ph = ph
    @label = label
    # ...
  end
  # ...
end

Now you can pass a number and a label, and you have a method defined to retrieve this label:

a = PhoneNumber.new('555-555-5555', :home)
#=> #<PhoneNumber:0x007fd7cb149fb0 @label=:home, @ph="(555) -55-5-5555">
[8] pry(main)> a.label
#=> :home