a = ['a', 'b', 'c'] a.each_with_index.reject {|el,i| i == 1}.each do |el,i| # do whatever with the element puts el end
Is IMHO a better way of doing the selection instead of using your own explicit if statement. I believe, however, that it will result in approximately the same performance as using if, maybe even slightly lower.
If after benchmarking as others have suggested you know that the time this takes is definitely slower than what you can allow it, and it is the selection causing the slowness then this can be easily modified to remove the selection in a number of ways:
a = ['a', 'b', 'c'] n = 1 (a.first(n) + a.drop(n + 1)).each do |el| # do whatever with the element puts el end
Unfortunately I believe this will also be slower than running the simple if. One that I believe might have the potential for speed is:
a = ['a', 'b', 'c'] n = 1 ((0...n).to_a+((n+1)...a.size).to_a).map{|i| a[i]}.each do |el| # do whatever with the element puts el end
But this again has a high possibility of being slower.
EDIT
Benchmark is in this gist. These results actually surprised me, reject is by far the slowest option, followed by the ranges. The highest performing after not removing the element at all was using first and drop to select all the elements around it.
The results as a percentage using no selection as a baseline:
with if 146% with first and drop 104% without if 100%
Obviously this is highly dependant on what you do with the elements, this was testing with probably the fastest operation Ruby can perform. The slower the operation the less difference these will have. As always: Benchmark, Benchmark, Benchmark