Skip to content

Instantly share code, notes, and snippets.

@ippeiukai
Created August 27, 2015 02:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ippeiukai/875f54e4260b587ee186 to your computer and use it in GitHub Desktop.
Save ippeiukai/875f54e4260b587ee186 to your computer and use it in GitHub Desktop.
Add `with_position_and_size` method to Enumerator. Those are quite handy inside a loop.
module EnumeratorWithPositionAndSize
# @yields [original_params, position_and_size]
# @yieldparam position_and_size [(Integer, Integer)] 2-element array of position (first being 1) and size; size may be nil (see Enumerator#size)
# @example
# %w[a b c d e].each.with_position_and_size { |char, (position, size)| puts "#{char} (#{position}/#{size})" }
def with_position_and_size
return to_enum(__method__) unless block_given?
my_size = self.size
self.with_index(1) do |original_params, position|
yield original_params, [position, my_size]
end
end
end
Enumerator.send(:include, EnumeratorWithPositionAndSize)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment