Posted viahttp://www.ruby-forum.com/.
You could do something like this. It only would work for exact
matches.
–Dale M.
class Array
def predecessor(index)
return nil if index == 0
self[index-1]
end
def successor(index)
return nil if index > (self.length-1)
self[index+1]
end
def near(value)
return nil unless index = self.index(value)
[ self.predecessor(index), self[index], successor(index) ]
end
end
a = [1, 2, 3, 4, 6, 7, 8, 9]
puts a.near(0).inspect # not found
puts a.near(1).inspect
puts a.near(2).inspect
puts a.near(3).inspect
puts a.near(4).inspect
puts a.near(5).inspect # not found
puts a.near(6).inspect
puts a.near(7).inspect
puts a.near(8).inspect
puts a.near(9).inspect
puts a.near(10).inspect # not found