Ruby Build an Address Book in Ruby Class Design Address Class: Part 2

Erik Nuber
Erik Nuber
20,627 Points

Code in lesson needs a small fix

It's a small thing but bothered me enough to go ahead and fix it. Based on the way the code is written, you are required to send in a 2nd Street line regardless of whether it is a blank represented by the "" that is run in the example. This is because the add_address method requires the argument.

This means that street_2 is not nil and never will be. So, in the address.rb file, the if statement will always be run and therefore we will always have that awkward space after the first street name and the comma is there is not an actual second street name.

To fix... could be simplified to check only for the "" however I left the nil statement in to cover all the bases just in case the contact.rb file gets changed in the future.

class Address
  attr_accessor :kind, :street_1, :street_2, :city, :state, :zip

  def to_s (format = "short")
      address = ""
      case format
        when "long"
          address += street_1 + "\n"
          address += street_2 + "\n" if (!street_2.nil? && street_2 != "")  #added here
          address += "#{city}, #{state} #{zip}"
        when "short"
          address += "#{kind}: "
          address += street_1
          if (!street_2.nil? && street_2 != "")  #added here 
            address += " "
            address += street_2
          end
          address += ", #{city} #{state}, #{zip}"
       end
    address
  end

end