Created
September 20, 2010 10:38
-
-
Save joecorcoran/587721 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Name | Department | Manager | Salary | |
---|---|---|---|---|
Robin Hood | 200 | |||
Arsene Wenger | Bar | Friar Tuck | 50 | |
Friar Tuck | Foo | Robin Hood | 100 | |
Little John | Foo | Robin Hood | 100 | |
Sam Allardyce | 250 | |||
Dimi Berbatov | Foo | Little John | 50 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def print_hierarchy filename, *args | |
# split the file by line break | |
file = File.read(filename).split("\n") | |
# remove the top row | |
top_row = file.shift.split(",") | |
# store column indices based on Column names passed as args | |
name_col = top_row.index(args[0] || "Name") | |
dept_col = top_row.index(args[1] || "Department") | |
mgr_col = top_row.index(args[2] || "Manager") | |
employees = [] | |
# add all employees to array | |
file.each do |line| | |
employees << line.split(",") | |
end | |
# push employees into last element of their respective managers' arrays | |
employees.each do |e| | |
e << employees.select { |x| x[mgr_col] == e[name_col] } | |
end | |
# run print_employee through managers and their employees | |
employees.delete_if { |e| !e[mgr_col].empty? }.each do |e| | |
print_employee e, 0, name_col, dept_col | |
end | |
end | |
def print_employee employee, level, name_col, dept_col | |
# add indentaion characters to line depending on level of employee | |
indent = "" + (">> " * level) | |
# if employee has no manager... | |
dept = (employee[dept_col].empty?) ? "Manager" : employee[dept_col] | |
puts indent + employee[name_col] + " (" + dept + ")" | |
# call recursively if employee has any managed employees | |
if (employee.last.is_a?(Array) && !employee.last.empty?) | |
level += 1 | |
employee.last.each do |e| | |
print_employee e, level, name_col, dept_col | |
end | |
end | |
end | |
print_hierarchy ARGV[0], "Name", "Department", "Manager" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment