Sunday, 26 October 2025

Manager

require 'json' # Define the file to store employee data DATA_FILE = 'employees.json' # Load existing employees from file or initialize empty array def load_employees if File.exist?(DATA_FILE) JSON.parse(File.read(DATA_FILE)) else [] end end # Save employees to file def save_employees(employees) File.write(DATA_FILE, JSON.pretty_generate(employees)) end # Display the main menu def display_menu puts "\nEmployee Management System" puts "1. List Employees" puts "2. Add Employee" puts "3. Update Employee" puts "4. Delete Employee" puts "5. Exit" print "Choose an option: " end # List all employees def list_employees(employees) puts "\nEmployee List:" if employees.empty? puts "No employees found." else employees.each_with_index do |emp, index| puts "#{index + 1}. #{emp['name']} - #{emp['position']} - $#{emp['salary']}" end end end # Add a new employee def add_employee(employees) print "Enter name: " name = gets.chomp print "Enter position: " position = gets.chomp print "Enter salary: " salary = gets.chomp.to_f employees << { 'name' => name, 'position' => position, 'salary' => salary } puts "Employee added successfully." end # Update an existing employee def update_employee(employees) list_employees(employees) print "Enter the number of the employee to update: " index = gets.chomp.to_i - 1 if index >= 0 && index < employees.size print "Enter new name (leave blank to keep current): " name = gets.chomp print "Enter new position (leave blank to keep current): " position = gets.chomp print "Enter new salary (leave blank to keep current): " salary_input = gets.chomp employee = employees[index] employee['name'] = name unless name.empty? employee['position'] = position unless position.empty? employee['salary'] = salary_input.to_f unless salary_input.empty? puts "Employee updated successfully." else puts "Invalid selection." end end # Delete an employee def delete_employee(employees) list_employees(employees) print "Enter the number of the employee to delete: " index = gets.chomp.to_i - 1 if index >= 0 && index < employees.size employees.delete_at(index) puts "Employee deleted successfully." else puts "Invalid selection." end end # Main program loop employees = load_employees loop do display_menu choice = gets.chomp case choice when '1' list_employees(employees) when '2' add_employee(employees) save_employees(employees) when '3' update_employee(employees) save_employees(employees) when '4' delete_employee(employees) save_employees(employees) when '5' puts "Exiting..." break else puts "Invalid option, please try again." end end

No comments:

Post a Comment