Ruby Build an Address Book in Ruby Search Searching by Phone Number

kabir k
PRO
kabir k
Pro Student 18,036 Points

phone_number vs. number

In the find_by_phone_number(number) method below, I know phone_number is an item in the phone_numbers array, but how is it different from the attribute accessor number in the PhoneNumber class? Are they the same?

Also, how is number different from phone_number in the inner each iteration of the find_by_phone_number(number) method?

def find_by_phone_number(number)
  results = []
  search = number.gsub("-", "")
  contacts.each do |contact|
    contact.phone_numbers.each do |phone_number|
      if phone_number.number.gsub("-", "").include?(search)
        results.push(contact) unless results.include?(contact)
      end
    end
  end
  print_results("Phone search results (#{search})", results)
end

For instance, in the inner loop, why is it?

if phone_number.number.gsub("-", "").include?(search)
    # line of code
end

and not something like this (without number):

if phone_number.gsub("-", "").include?(search)
    # line of code
end

1 Answer

Great question. One of the main reasons is that phone_number is actually an instance of the class PhoneNumber. If you look into the workspaces you can see that each phone number has two attributes, kind and number.

In each iteration, we're simply pulling out checking only the number.

PhoneNumber class from the video.

class PhoneNumber
  attr_accessor :kind, :number

  def to_s
    "#{kind}: #{number}"
  end
end