Created
August 4, 2017 07:20
-
-
Save Sihui/36354825e9a1542674953316cbf9d885 to your computer and use it in GitHub Desktop.
Design Pattern: Iterator and Movie Collections
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
class HashIterator | |
attr_reader :collection, :keys | |
attr_accessor :current_index | |
def initialize(collection) | |
@collection = collection | |
@keys = collection.keys | |
@current_index = 0 | |
end | |
def has_next? | |
current_index < keys.length | |
end | |
def next | |
raise 'No more item left.' unless has_next? | |
item = collection[keys[current_index]] | |
self.current_index += 1 | |
item | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment