From: David Alan Black Date: 2001-11-17T08:28:34+09:00 Subject: [ruby-talk:25686] Re: Arrays, iterators, and map/collect Hi -- On Sat, 17 Nov 2001, Hal E. Fulton wrote: > From: Robert Feldt > > > On Fri, 16 Nov 2001, Hal E. Fulton wrote: > > > > > But what if I want to do an operation > > > conditionally? Is this still a good way to do it, > > > in a case where the mapped value is > > > sometimes/always the same as the original? > > > > > > strings.map! { |s| if s[0]==?a then s else "pre." + s end } > > > > > I would do it like this but allow myself to shorten it to > > > > strings.map! {|s| s[0]==?a ? s : ("pre." + s)} > > > > since its a one-liner. > > > > Don't you feel it is natural? Why? > > > > I'm having difficulty expressing myself. > > This example is natural enough. > > One problem I have is: When I travel through > an array, I expect to use an iterator. > > What if the map! operation is really only a > side effect? I guess it is possible to do > other stuff inside the block, but that makes > it less obvious what is happening. > > I guess I would like to iterate through an array > performing arbitrary operations and have the > option to change the values of array elements > if I wished. "replace" is OK I suppose... I haven't > tried it. > > I don't like the idiom of explicitly indexing into > the array for this case... If you *really* want to see side-effect programming: strings = %w[ alpha beta gamma ] strings.find_all {|s| s[0,0] = "pre." if s[0] == ?a} :-) I think the map! version is pretty clear, since that's what map! basically does -- though I have to say, sometimes it looks/feels better to me to do: strings = strings.map { ... } (though I don't know if there are performance considerations). David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav