Codes316 Codes316 - 1 year ago 62
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 = ('(555) 555-5555', :home)
=>(555) 555-5555 (home)


MyContact2. = (' 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, "-")
def to_s
def area_code
def prefix
def root
print "Please enter a phone number: "
puts a =
puts a.area_code
puts a.prefix
puts a.root

Answer Source

Just extend your initialize method to accept more arguments:

class PhoneNumber

  attr_reader :label

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

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

a ='555-555-5555', :home)
#=> #<PhoneNumber:0x007fd7cb149fb0 @label=:home, @ph="(555) -55-5-5555">
[8] pry(main)> a.label
#=> :home
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download