Last active
December 14, 2015 13:59
-
-
Save padde/5097476 to your computer and use it in GitHub Desktop.
Array#each_with_position
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 | |
| attr_accessor :idx, :max | |
| def initialize arr | |
| self.max = arr.size | |
| end | |
| def pos | |
| idx + 1 | |
| end | |
| def inside? range | |
| range.include? pos | |
| end | |
| def nth? i | |
| pos == i | |
| end | |
| def first? | |
| nth? 1 | |
| end | |
| def middle? | |
| not first? and not last? | |
| end | |
| def last? | |
| nth? max | |
| end | |
| def inside range | |
| yield if inside? range | |
| end | |
| def nth i | |
| yield if nth? i | |
| end | |
| def first | |
| yield if first? | |
| end | |
| def middle | |
| yield if middle? | |
| end | |
| def last | |
| yield if last? | |
| end | |
| end | |
| def each_with_position | |
| pos = Array::Position.new self | |
| each_with_index do |x,i| | |
| pos.idx = i | |
| yield x, pos | |
| end | |
| end | |
| end | |
Author
padde
commented
Mar 6, 2013
Author
%w{some short simple words}.each_with_position do |x, pos|
pos.first do
puts "#{x} is first"
end
pos.inside 2..3 do
puts "#{x} is second or third"
end
pos.middle do
puts "#{x} is middle"
end
pos.last do
puts "#{x} is last"
end
end
# some is first
# short is second or third
# short is middle
# simple is second or third
# simple is middle
# words is last
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment