----- Original Message ----- From: Robert Feldt <feldt / ce.chalmers.se> To: ruby-talk ML <ruby-talk / ruby-lang.org> Sent: Thursday, November 15, 2001 11:21 PM Subject: [ruby-talk:25385] Re: Arrays, iterators, and map/collect > On Fri, 16 Nov 2001, Joel VanderWerf wrote: > > > "Hal E. Fulton" wrote: > > > > > strings.each_with_index do |s,i| > > > strings[i] = "pre." + s if s[0] != ?a > > > end > > > > > > The above works, but seems ugly. > > > > strings.select { |s| s[0]!=?a }.each { |s| s[/^/] = "pre." } > > > > Of course, this destructively modifies the strings, which your code > > doesn't do... So this suggestion isn't really about iterators, but about > > a way to do << at the beginning of a string. > > > I haven't followed this thread so may be out of line but there is also > > strings.select {|s| s[0] != ?a}.each {|s| s[0,0] = "pre."} > > However, the two iterations and extra Array creation is > more costly than Hal's single iteration. I guess you'll hardly notice the > difference for small arrays though... Thanks for comments, both of you... The issue of prepending to a string (though that really isn't an English word :)) is not the interesting part to me... I'm trying to figure out the proper way, in general, to avoid the each_with_index weirdness. I guess the other question is: Is map! inefficient about mapping an object onto itself? I.e., what if I left out the if? In some sense I am bothered that x += y creates a new object. I don't see any way around it, though. I did toy with the (bad) idea of a ":=" assignment in Ruby, which guaranteed to re-use the object on the lefthand side... :) Then one could do: strings.each {|s| s:="pre."+s } with impunity. Hal