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

Daniele Santos
Daniele Santos
16,451 Points

It works on my editor, but it won't work on Workspaces

So, here's the code I have on my editor that runs address: class Address attr_accessor :kind, :street_1, :street_2, :city, :state, :postal_code, :address

def initialize(kind, street_1, street_2, city, state, postal_code, address) @kind = kind or '' @street_1 = street_1 or '' @street_2 = street_2 or '' @city = city or '' @state = state or '' @postal_code = postal_code or '' @address = to_s("short") 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

newAdd = Address.new("home", "Allerstr.", "10", "Berlin", "Brandenburg", "12049", to_s) puts newAdd.to_s

address.rb
class Address
  attr_accessor :kind, :street_1, :street_2, :city, :state, :postal_code, :address
  def initialize(kind, street_1, street_2, city, state, postal_code, address)
    @kind = kind or ''
    @street_1 = street_1 or ''
    @street_2 = street_2 or ''
    @city = city or ''
    @state = state  or ''
    @postal_code = postal_code or ''
    @address = address 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

newAdd = Address.new("home", "Allerstr.", "10", "Berlin", "Brandenburg", "12049", to_s)
puts newAdd.to_s

2 Answers

Jay Padzensky
Jay Padzensky
4,704 Points

Hi Daniele,

With Code Challenges, often copying and pasting your task's instructions verbatim into the Community search bar will yield some results. For task one of this Code Challenge, I found these threads. I hope one will help you out!