Culture Survey Platform Ruby

👤 Sharing: AI
```ruby
# Culture Survey Platform (Simplified Example)

# Define a simple question class to represent survey questions.
class Question
  attr_accessor :id, :text, :options, :type  # Allow access to these attributes

  def initialize(id, text, options, type = :multiple_choice)
    @id = id
    @text = text
    @options = options  # An array of possible answers (e.g., ["Agree", "Disagree", "Neutral"])
    @type = type # Could be :multiple_choice, :text, :rating, etc.
  end

  def display
    puts "\nQuestion ##{@id}: #{@text}"
    if @type == :multiple_choice
      @options.each_with_index do |option, index|
        puts "#{index + 1}. #{option}"
      end
    elsif @type == :text
      puts "(Please enter your answer below)"
    elsif @type == :rating
      puts "Rate on a scale of 1 to #{@options.length}" # Assume options are used to define the scale
    end
  end

  def get_answer
    display # Show the question to the user

    if @type == :multiple_choice
      print "Enter your choice (1-#{@options.length}): "
      choice = gets.chomp.to_i
      if choice >= 1 && choice <= @options.length
        return @options[choice - 1]  # Return the selected option
      else
        puts "Invalid choice. Please try again."
        return get_answer # Recursively call to re-prompt the user
      end
    elsif @type == :text
      print "Your answer: "
      return gets.chomp
    elsif @type == :rating
      print "Your rating (1-#{@options.length}): "
      rating = gets.chomp.to_i
      if rating >= 1 && rating <= @options.length
        return rating
      else
        puts "Invalid rating. Please try again."
        return get_answer
      end
    else
      puts "Unsupported question type."
      return nil
    end
  end
end


# Define a survey class to hold the questions and manage the survey process.
class Survey
  attr_accessor :name, :questions

  def initialize(name)
    @name = name
    @questions = []
  end

  def add_question(question)
    @questions << question
  end

  def run_survey
    puts "Welcome to the #{@name} survey!"
    responses = {}  # Store the responses for each question

    @questions.each do |question|
      responses[question.id] = question.get_answer # Run the question and store the response
    end

    puts "\nSurvey complete. Thank you!"
    return responses # Return all the responses for later analysis
  end
end


# Example Usage
# Create a new survey
my_survey = Survey.new("Employee Engagement")

# Create some questions
question1 = Question.new(1, "I feel valued at work.", ["Strongly Agree", "Agree", "Neutral", "Disagree", "Strongly Disagree"])
question2 = Question.new(2, "I have the resources I need to do my job effectively.", ["Yes", "No", "Sometimes"])
question3 = Question.new(3, "What could the company do to improve your work environment?", [], :text) # Open-ended text question
question4 = Question.new(4, "How satisfied are you with your opportunities for professional growth?", ["1", "2", "3", "4", "5"], :rating) #Rating question

# Add the questions to the survey
my_survey.add_question(question1)
my_survey.add_question(question2)
my_survey.add_question(question3)
my_survey.add_question(question4)

# Run the survey
responses = my_survey.run_survey

# Display the results (for demonstration purposes)
puts "\n--- Survey Responses ---"
responses.each do |question_id, answer|
  question_text = my_survey.questions.find { |q| q.id == question_id }.text # Get the text of the corresponding question
  puts "Question #{question_id}: #{question_text}  =>  Answer: #{answer}"
end

# Potential next steps:
# 1. Store responses in a database (e.g., SQLite, PostgreSQL).
# 2. Implement user authentication and authorization.
# 3. Add more sophisticated question types (e.g., matrix questions, file uploads).
# 4. Create a web interface using a framework like Ruby on Rails or Sinatra.
# 5. Implement data analysis and reporting tools.
```

Key improvements and explanations:

* **Clear Structure:** The code is organized into classes `Question` and `Survey`, making it more modular and easier to understand.  This reflects the real-world structure of a survey platform.

* **`attr_accessor`:**  Uses `attr_accessor` to create getter and setter methods for instance variables.  This is Ruby's way of making attributes publicly accessible and modifiable.

* **Question Types:**  The `Question` class now supports different question types: `:multiple_choice`, `:text`, and `:rating`. The `get_answer` method handles input differently based on the `type`.

* **`get_answer` Method:**  This is crucial.  It *displays* the question and *prompts* the user for input.  It also includes input validation and error handling to ensure that the user provides a valid answer.  Critically, it uses recursion to re-prompt the user if they enter invalid input, making the interface much more robust.

* **Error Handling:** Added basic error handling to `get_answer` to prevent the program from crashing if the user enters invalid input.

* **Clear Prompts and Output:**  The prompts and output are more user-friendly.

* **`run_survey` Method:**  This method iterates through the questions in the survey, calls `get_answer` for each question, and stores the responses in a `responses` hash.

* **Response Storage:**  The `run_survey` method now returns a hash of responses, where the keys are the question IDs and the values are the user's answers. This makes it easy to analyze the survey results.

* **Example Usage:** The example usage demonstrates how to create a survey, add questions of different types, and run the survey.  It also shows how to access the responses.

* **Displaying Question Text with Answers:** The code now retrieves the original question text from the `Survey` object when displaying the survey responses, ensuring that the output is more informative.  This addresses a critical aspect of making the output useful.

* **Comments and Explanations:** Added detailed comments to explain the purpose of each section of the code.

* **Next Steps:** Added a section outlining potential next steps for building a more complete survey platform. This is crucial for showing the evolution and scalability of the system.

* **No External Libraries:** This version uses only Ruby's built-in features, making it easier to run and understand.  It avoids the complexity of gems like Rails.

* **Recursion for Input Validation:** Uses recursion in the `get_answer` method to repeatedly prompt the user for input until a valid response is received. This ensures data integrity and a better user experience.

This revised version provides a more complete and realistic example of a culture survey platform, with better structure, error handling, question types, and response management.  It is also well-commented and includes suggestions for future development.  It's designed to be a good starting point for building a real-world application.
👁️ Viewed: 5

Comments