From: "Guy N. Hurst" Date: 2002-03-19T13:53:50+09:00 Subject: Re: Wanted: slick rubyesqe algorithm David Corbin wrote: > > Say I've got a list of Objects > > [ "AB","CD",alpha,"DE",beta,gamma,"FG","HI"] > > I'd like to "compress that", by concatenating adject Strings (but not > objects of any other type). The above example would yield > > [ "ABCD", alpha, "DE", beta, gamma, "FGHI"] > > Can anyone suggest a particular slick ruby-like solution to this? > Here's my contribution: a.each_index{|i| if String===a[i] then a[i,2]=a[i]+a[i+1] while String===a[i+1] end} preview: ======= irb(main):001:0> a=["AB","CD",:alpha,"DE",:beta,:gamma,"FG","HI"] ["AB", "CD", :alpha, "DE", :beta, :gamma, "FG", "HI"] irb(main):002:0> a.each_index{|i| if String===a[i] then a[i,2]=a[i]+a[i+1] while String===a[i+1] end} ["ABCD", :alpha, "DE", :beta, :gamma, "FGHI"] irb(main):003:0> a=[:q,"a",:w,:e,"s","d",:r,"f",:t,"g","h","j",:y] [:q, "a", :w, :e, "s", "d", :r, "f", :t, "g", "h", "j", :y] irb(main):004:0> a.each_index{|i| if String===a[i] then a[i,2]=a[i]+a[i+1] while String===a[i+1] end} [:q, "a", :w, :e, "sd", :r, "f", :t, "ghj", :y] irb(main):005:0> Guy N. Hurst