Skip to content

Instantly share code, notes, and snippets.

@padde
Last active December 14, 2015 14:08
Show Gist options
  • Select an option

  • Save padde/5098018 to your computer and use it in GitHub Desktop.

Select an option

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.
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