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

Sean Flanagan
Sean Flanagan
33,220 Points

Task 2: Call the to_s method on the address variable

Hi. I can't make this work.

My code:

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
end

address = Address.new("Home", "Street", "Village", "Town", "County", "Postcode")
def to_s
   address
end

Does anyone know where I'm going wrong please?

Thanks in advance. :)

1 Answer

Seth Reece
Seth Reece
32,864 Points

Hi Sean,

You already have to_s defined in your class. You don't need to define it a gain, just call it. e.g.

# This will pass and use the default form 'short'
address.to_s()
# since there is also a 'long' format defined you could use:
address.to_s('long')
Sean Flanagan
Sean Flanagan
33,220 Points

That makes sense. Thanks Seth. Up vote and Best Answer for you.

Sean :)