From: Robert Klemme Date: 2009-05-14T16:46:03+09:00 Subject: Re: find previous & next in array 2009/5/14 John Griffiths : > hi, anyone know how to do this? > > basically i've got an array of items > > a = ['a','b','c','d'] > > now given i can find the position of say 'c' using .index('c'), how do i > get the positions of the ones previous & next to it. > > a recursive routine would probably do it, but looking for something more > flash > > any ideas? Depends on what you need to do. Do you need those indexes or do you only need access to those elements? There are a few variants, but the nice ones aren't really safe against edge cases (first and last element): irb(main):004:0> a = ['a','b','c','d'] => ["a", "b", "c", "d"] irb(main):005:0> i = a.index('c') and a[i-1 .. i+1] => ["b", "c", "d"] irb(main):006:0> a[a.index('c') - 1, 3] rescue nil => ["b", "c", "d"] irb(main):007:0> i = a.index('a') and a[i-1 .. i+1] => [] irb(main):008:0> a[a.index('a') - 1, 3] rescue nil => ["d"] The safest is probably i = a.index('c') if i predecessor = i > 0 ? a[i -1] : nil successor = a[i + 1] # safe! end Or as a variant i = a.index('c') and begin predecessor = i > 0 ? a[i -1] : nil successor = a[i + 1] # safe! end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/