From: ao tianlong Date: 2006-11-29T14:31:22+09:00 Subject: Re: array question ------=_Part_9139_8912241.1164778279948 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline 2006/11/23, William James : > > Robert Klemme wrote: > > On 21.11.2006 10:16, William James wrote: > > > Robert Klemme wrote: > > >> On 21.11.2006 08:18, William James wrote: > > >>> Li Chen wrote: > > >>>> Hi all, > > >>>> > > >>>> I want to build a new array from an old one with every element > being > > >>>> duplicated except the first and last element. And here are my > codes. I > > >>>> wonder if this is a real Ruby way to do it. > > >>>>> array=[1,2,3,4,5,6,7,8,9,10] > > >>> => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > >>>>> array.zip(array).flatten[1..-2] > > >>> => [1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10] > > >> That's cute! I have another one with #inject (of course): > > >> > > >> irb(main):007:0> arr=(1..10).to_a > > >> => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > >> irb(main):008:0> copy=[] > > >> => [] > > >> irb(main):009:0> arr.inject{|a,b| copy << a << b; b} > > >> => 10 > > >> irb(main):010:0> copy > > >> => [1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10] > > > > > > This demonstrates an excellent understanding of inject and > > > > Thank you! > > > > > is a good way to eliminate the somewhat ugly [1..-2]. > > > > Well, you can use [1...-1] instead. :-) > > Ha, ha. Also ugly. > > > > > > Here's a prolix way of avoiding array indexing while using zip: > > > > > > copy=arr.dup; copy.shift; copy.pop > > > arr.zip(copy).flatten.compact > > > > You can copy and reduce in one step: > > > > >> arr=(1..10).to_a > > => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > >> arr.zip(arr[1...-1]).flatten.compact > > => [1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10] > > > > Or, more efficient > > > > >> arr.zip(arr[1...-1]).flatten!.compact! > > => [1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10] > > But it has "[1...-1]"! Indexing with literal numbers is so horrid. > > > > > Cheers > > > > robert your name looks like a chinese , and i'm too. > > what about this code ? > > irb(main):008:0> %w{a b c d e f g h i j k l m n o p q r s t u v w x y > z}.map{|i| i = [i,i]}.flatten[1..-2] > => ["a", "b", "b", "c", "c", "d", "d", "e", "e", "f", "f", "g", "g", > "h", "h", "i", "i", "j", "j", "k", "k", "l", "l", "m", "m", "n", "n", > "o", "o", "p", "p", "q", "q", "r", "r", "s", "s", "t", "t", "u", "u", > "v", "v", "w", "w", "x", "x", "y", "y", "z"] > ------=_Part_9139_8912241.1164778279948--