From: "Guy N. Hurst" Date: 2002-03-19T23:20:30+09:00 Subject: Re: Wanted: slick rubyesqe algorithm Marko Schulz wrote: > > On Tue, Mar 19, 2002 at 01:53:50PM +0900, Guy N. Hurst wrote: > > > > 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} > > That's nice. I would prefer a little bit more readable version: > > a.each_index do |i| > if String===a[i] > a[i,2]=a[i]+a[i+1] while String===a[i+1] > end > end > > My eyes are not adapted to Module#===Object either, but if one is used > to it, this looks like a nice shortcut to Object#type==Module. > > I am always a little afraid to modify a structure I am iterating > over. Different languages and libraries are differently robust > concerning this. Is it generally OK to do this in ruby? > Well, if the method were made to self-modify, it may be considered dangerous and marked with '!' unless it is expected to modify the structure, like Array#shift or #pop. Here is a safer approach which uses a copy: class Array def join_adjacent_strings a=self.dup a.each_index do |i| if String===a[i] a[i,2]=a[i]+a[i+1] while String===a[i+1] end end a end end As for whether it is generally ok, I think that depends on your target audience. As for me, I regularly do so for the power it offers. Of course, I also like making self-modifying CGI scripts ;-) To me, it is not so much a structure as it is a piece of modeling clay. Ruby allows me to be artistic in my programming, and that is one more reason I like ruby. Guy N. Hurst