Skip to content

Instantly share code, notes, and snippets.

@voleinikov
Created January 13, 2013 23:24
Show Gist options
  • Save voleinikov/4526780 to your computer and use it in GitHub Desktop.
Save voleinikov/4526780 to your computer and use it in GitHub Desktop.
# Class counting example.rb
# An example of using a hash to count attributes stored in a class.
class Course
attr_accessor :name, :dept, :credits
def initialize (name, dept, credits)
@name = name
@dept = dept
@credits = credits
end
end
def count_dept_credits_taken(array_of_course_objects)
dept_credits = Hash.new(0)
array_of_course_objects.each do |course|
dept_credits[course.dept] += course.credits
end
dept_credits
end
# English courses
basic_english = Course.new("English 101", "English", 5)
great_novels = Course.new("English 132", "English", 3)
biz_writing = Course.new("English 201", "English", 2)
# A non-English Course
computers = Course.new("CSE 142", "Comp-Sci", 5)
course_list = [basic_english, great_novels, biz_writing, computers]
p count_dept_credits_taken(course_list)
# Returns {"English" => 10, "Comp-Sci" = 5}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment