Ruby Build an Address Book in Ruby Class Design Initializing and Calling Methods

Sarah A. Morrigan
Sarah A. Morrigan
14,299 Points

address = Address.new does not define variable address?

When address = Address.new is invoked it generates an empty variable address whereas the class Address is called from ./address.rb.

But somehow code challenge keeps telling me that "address" is an invalid variable.

address.rb
class Address
  attr_accessor :kind, :street_1, :street_2, :city, :state, :postal_code

  def initialize
    @addresses = []
  end

  def add_address(kind, street_1, street_2, city, state, postal_code)
    address = Address.new
    @kind = kind or ''
    @street_1 = street_1 or ''
    @street_2 = street_2 or ''
    @city = city or ''
    @state = state  or ''
    @postal_code = postal_code or ''
  end

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

1 Answer

William Li
PRO
William Li
Pro Student 26,793 Points

Hi, Sarah A. Morrigan

The problem is in this block of code.

def initialize
    @addresses = []
  end

The challenge is asking for

initialize a variable called address which will be a new instance of the Address class.

To initialize a new instance of class, you have to do so outside of the class definition; also, there's no need to make any change the class definition body.

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

  def initialize(kind, street_1, street_2, city, state, postal_code)
    @kind = kind or ''
    @street_1 = street_1 or ''
    @street_2 = street_2 or ''
    @city = city or ''
    @state = state  or ''
    @postal_code = postal_code or ''
  end

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

# initialize instance of  Address class with arbitrary values
address = Address.new('kind','st1','st2','city','state','zip')

Hope that helps.