Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.