Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
OOP attempt at redoing a code attempt by someone which is basically a quiz which returns facts about a certain selected city
class Quiz
  attr_reader :cities

  def initialize
    @cities = get_cities   
    introduction
  end

  def get_cities
    ObjectSpace.each_object(Class).select { |klass| klass < City }.collect{ |c| c.new}
  end

  def introduction
    city_names = @cities.collect {|c| c.name }
    cities_joined = city_names.join("\n")
    puts "\n\n\nWelcome to fact_bot! fact_bot knows some facts about the following cities: \n#{cities_joined}"
  end

  def question   
    while true
      city = city_factory
      puts city.facts
    end
  end

  def city_factory
    while true 
      puts "Type any city listed to see facts |'exit' to leave | 'list' to view cities | \n"
      answer = gets.chomp     
      case answer.downcase
      when "sydney"
        return CitySYD.new
      when "san fransisco"
        return CitySF.new
      when "london"
        return CityLN.new
      when "exit"
        abort
      when "list"
        introduction     
      else 
        puts "Spelling mistake - please type the city correctly\n"       
      end
    end
  end
end

class City
  attr_reader :name, :facts

  def initialize
    # if you had a database you could probably get the values with 
    # something like this.
    # but we don't have such a facility available to us
    # So i thought to employ polymorphism and a factory method
    # to get us the result we need
    # @name = get_name()
    # @facts = get_facts()
  end

  def get_name
    ""
  end

  def get_facts
    []
  end
end

class CitySF < City
  def initialize
    @name = "San Fransisco"
    @facts = get_facts()
  end

  def get_facts
    ["Population is 10m", "USA"]
  end
end

class CityLN < City
  def initialize
    @name = "London"
     @facts = get_facts()
  end

  def get_facts
    ["Population is 20m", "England, UK"]
  end
end


class CitySYD < City
  def initialize
    @name = "Sydney"
     @facts = get_facts()
  end

  def get_facts
    ["Population is 4m", "Australia"]
  end

end

q = Quiz.new
q.question
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.