Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save padde/5097476 to your computer and use it in GitHub Desktop.
Array#each_with_position
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
@padde
Copy link
Author

padde commented Mar 6, 2013

[1,2,3,4,5].each_with_position do |x,pos|
  puts "#{x} is first"  if pos.first?
  puts "#{x} is third"  if pos.nth? 3
  puts "#{x} is middle" if pos.middle?
  puts "#{x} is last"   if pos.last?
  puts
end

#1 is first
# 
#2 is middle
# 
#3 is third
#3 is middle
# 
#4 is middle
# 
#5 is last

@padde
Copy link
Author

padde commented Mar 6, 2013

%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