Skip to content

Instantly share code, notes, and snippets.

@gar
Created September 26, 2010 09:56
Show Gist options
  • Save gar/597788 to your computer and use it in GitHub Desktop.
Save gar/597788 to your computer and use it in GitHub Desktop.
class ReportCard
def initialize(print_strategy)
@print_strategy = print_strategy.new
@grades = Hash.new
end
def add_grade(subject, grade)
@grades[subject] = grade
end
def print
puts @print_strategy.print(@grades)
end
end
class CSVStrategy
def print(grades)
output = ["Subject,Grade"]
for subject in grades.keys
output << "#{subject},#{grades[subject]}"
end
output.join("\n")
end
end
class HTMLStrategy
def print(grades)
output = ["<table>"]
output << "<th><td>Subject</td><td>Grade</td></th>"
for subject in grades.keys
output << "<tr><td>#{subject}</td><td>#{grades[subject]}</td></tr>"
end
output << "</table>"
output.join("\n")
end
end
csv_report_card = ReportCard.new(CSVStrategy)
csv_report_card.add_grade("English", "A")
csv_report_card.add_grade("Maths", "B+")
csv_report_card.add_grade("French", "C")
csv_report_card.print #=> will print out the above in CSV format
html_report_card = ReportCard.new(HTMLStrategy)
html_report_card.add_grade("English", "A")
html_report_card.add_grade("Maths", "B+")
html_report_card.add_grade("French", "C")
html_report_card.print #=> will print out the above in HTML format
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment