Skip to content

Instantly share code, notes, and snippets.

@canadaduane
Created December 5, 2012 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save canadaduane/4219039 to your computer and use it in GitHub Desktop.
Save canadaduane/4219039 to your computer and use it in GitHub Desktop.
Make an Iterator
# Here's my method that loops over a collection and yields a block
def tardies_for_student(student_id, now=Time.zone.now)
submissions_by_student_id[student_id].each do |submission|
assignment = @assignments_by_id[submission.assignment_id]
yield build_tardy(assignment, submission, now)
end
end
# now I know I can do this...
tardies_for_student(1) do |tardy|
# do something with tardy
end
# but I want to be able to do this...
tardies_for_student(1).each do |tardy|
# do something with tardy
end
# OR
tardies_for_student(1).map do |tardy|
# do something with tardy
end
@jenseng
Copy link

jenseng commented Dec 5, 2012

class TardiesForStudent
  include Enumerable

  def initialize(student_id, now = Time.zone.now)
     @submissions = submissions_by_student_id[student_id]
     @now = Time.zone.now
  end

  def each
    @submissions.each do |submission|
      assignment = @assignments_by_id[submission.assignment_id]
      yield build_tardy(assignment, submission, now)
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment