From: "Hal E. Fulton" Date: 2001-11-16T13:47:01+09:00 Subject: [ruby-talk:25383] Arrays, iterators, and map/collect Hello all... This may be two or more questions. My thoughts are a little disorganized. :) Sometimes I want to do something to each item in an array. An iterator seems natural for this (to me). strings = %w[ alpha beta gamma ] strings.each { |s| s << ".post" } This works because << operates on the object, not the variable. But if I do this: strings.each { |s| s = "pre." + s } obviously it doesn't work because we're creating a new object. On the other hand, map! (or collect!) will do this just fine. strings.map! { |s| s = "pre." + s } 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 } This, of course, doesn't work: strings.each do |s| s = "pre." + s if s[0] != ?a end I really don't like the case where each_with_index is used and the array is referenced inside the block of its own iterator. (Sometimes I do it, though, depending on circumstances.) strings.each_with_index do |s,i| strings[i] = "pre." + s if s[0] != ?a end The above works, but seems ugly. Comments, anyone? Hal