From: GOTO Kentaro Date: 2001-11-16T15:54:27+09:00 Subject: [ruby-talk:25393] Re: Arrays, iterators, and map/collect In message "[ruby-talk:25387] Re: Arrays, iterators, and map/collect" on Fri, 16 Nov 2001 14:34:03 +0900, "Hal E. Fulton" writes: > ----- Original Message ----- > From: Robert Feldt > To: ruby-talk ML > Sent: Thursday, November 15, 2001 11:21 PM > Subject: [ruby-talk:25385] Re: Arrays, iterators, and map/collect > 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. When each member is a kind of container, `replace' works. strings = %w[ alpha beta gamma ] strings.each do |s| s.replace("pre.#{s}") if /^a/ =~ s end p strings #=> ["pre.alpha", "beta", "gamma"] > 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. Now, the operation is not to the element but the array. It should not be a operation to block params, but should be one to the array itself, IMHO. However, each_index looks ugly. So, maybe gsub like interface is needed. E.g.: class Array def change_if(arg) if block_given? if arg.is_a? Proc each_with_index{|e,i| self[i] = yield(e) if arg.call(e)} else each_with_index{|e,i| self[i] = yield(e) if arg === e} end end end end strings = %w[ alpha beta gamma ] strings.change_if(/^a/) do |s| "pre." + s end p strings -- Gotoken