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

Daniel Wise
Daniel Wise
9,119 Points

Do not understand what is wrong here

It seems I am doing this correctly. But it keeps saying that the address variable is not being defined.

address.rb
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
  address = Address.new('Short', '11 Berryback Rd', '123 Whatroad Rd', 'Smittytown', 'NC', '11234') 
end

3 Answers

warborn
warborn
7,116 Points

Try creating the address object after the last "end" keyword, you are creating it inside the Address class itself

Sidney Casagrande
Sidney Casagrande
7,035 Points

I'm not a Ruby expert but my first thought would be that you are defining address inside a definition (to_s) and calling it outside of the to_s definition. At the call (address = Address.new('Short', '11...blah...')) I would say that you would have lost memory/scope of address inside to_s?

Daniel Wise
Daniel Wise
9,119 Points

Thanks for trying but I gave your idea a shot and it didn't work :(

Daniel Wise
Daniel Wise
9,119 Points

Thanks everyone for your help! I just kept trying my code and it worked. I think I needed to move it down a spot. That was all haha.