From: "J. B. Rainsberger" Date: 2006-11-21T15:03:42+09:00 Subject: Re: array question Daniel N wrote: > On 11/21/06, Wilson Bilkovich wrote: >> >> >> > >> >> A couple of ways: (there are probably dozens more) >> # given: >> array = [1,2,3,4,5,6] >> >> # 1. >> new_array = array[1..-2] > > > This would not duplicate the inner elements though. > > To build on this one. > b = a.inject( [] ) { |a,e| a << [e,e]}.flatten[1..-2] > > This looks pretty jarring to my eyes though :( I would use map over inject into []: b = a.map { |each| [each,each] }.flatten[1..-2] Either that, or recognize that it's equivalent duplicating all except first and last. b = [a[0], a[1..-2].map { |each| [each, each] }.flatten, a[-1]] In either case, we can avoid the flatten entirely, at the expense of returning to inject: b = a.inject([]) {|sum, each| sum.concat([each, each])[1..-2] or b = [a[0], a[1..-2].inject([]) {|sum, each| sum.concat([each, each])}, a[-1]] Of course, if we know the items in the array are in ascending order, we can /really/ cheat: b = (a*2).sort[1..-2] That's as many as I could think of. -- J. B. (Joe) Rainsberger :: http://www.jbrains.ca Your guide to software craftsmanship JUnit Recipes: Practical Methods for Programmer Testing 2005 Gordon Pask Award for contribution Agile Software Practice