Created
June 13, 2011 03:44
-
-
Save dallas/1022290 to your computer and use it in GitHub Desktop.
Smart enumerator with smart enumerable items
This file contains hidden or 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 SmartEnumerator < Enumerator | |
attr_reader :length | |
def initialize(enumerable) | |
super | |
@length = enumerable.length | |
end | |
def each | |
self.each_with_index do |item, index| | |
yield SmartEnumerableItem.new(item, index, self.length) | |
end | |
end | |
end | |
class SmartEnumerableItem | |
def initialize(item, index, parent_length) | |
@item = item | |
@index = index | |
@parent_length = parent_length | |
end | |
def first? | |
@index.zero? | |
end | |
def last? | |
@index + 1 == @parent_length | |
end | |
def to_s | |
@item.to_s | |
end | |
def method_missing(name, *args, &block) | |
@item.send name, *args, &block | |
end | |
end |
This file contains hidden or 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
x = SmartEnumerator.new([1,2,3,4,5]) | |
x.each {|i| i.first? ? puts(i.to_s.inspect) : i.last? ? puts("#{i} is the last one") : puts(i**i)} | |
"1" | |
4 | |
27 | |
256 | |
5 is the last one |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment