Created
August 27, 2015 02:14
-
-
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.
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
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