Last active
December 14, 2015 14:08
-
-
Save padde/5098018 to your computer and use it in GitHub Desktop.
Array#each_with_position (cached) Useful if you call the pos methods often.
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 Array | |
| class Position | |
| def initialize ary | |
| @pos = 1 | |
| @max = ary.size | |
| @cache = Hash.new | |
| end | |
| def advance | |
| @pos += 1 | |
| @cache.clear | |
| end | |
| def inside? range | |
| return @cache[range] unless @cache[range].nil? | |
| @cache[range] = range.include? @pos | |
| end | |
| def nth? i | |
| inside? i..i | |
| end | |
| def middle? | |
| inside? 2..@max-1 | |
| end | |
| def first? | |
| nth? 1 | |
| end | |
| def last? | |
| nth? @max | |
| end | |
| %w{inside nth first middle last}.each do |pos_name| | |
| define_method pos_name do |*args, &block| | |
| block.call if block and send :"#{pos_name}?", *args, &block | |
| end | |
| end | |
| end | |
| def each_with_position | |
| pos = Position.new self | |
| each do |x| | |
| yield x, pos | |
| pos.advance | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment