Skip to content

Instantly share code, notes, and snippets.

@dallas
Created June 13, 2011 03:44
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 dallas/1022290 to your computer and use it in GitHub Desktop.
Save dallas/1022290 to your computer and use it in GitHub Desktop.
Smart enumerator with smart enumerable items
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
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