From: Siep Korteling Date: 2008-09-22T06:36:24+09:00 Subject: Re: Iterating through a string Ruby Fan wrote: > Stefano Crocco wrote: >> Alle Sunday 21 September 2008, Jody Glidden ha scritto: >>> If I try the following... >>> >>> "I love guitar playing".split {|s| s.capitalize}.join(" ") >>> >>> I would expect it to capitalize the first letter of each word but it >>> doesn't seem to work. >>> >>> Any hints on what I'm doing incorrectly? >> >> >> String#split doesn't take a block, so that the block you pass to it is >> ignored. What you wrote is equivalent to >> >> "I love guitar playing".split.join(" ") >> >> To do what you want, you need to call map on the array returned by >> String#split: >> >> "I love guitar playing".split.map{|s| s.capitalize}.join(" ") >> >> I hope this helps >> >> Stefano > > Ahh, I understand. I must have missed the map/collect functionality. > > Thanks. "I love guitar playing".split.each{|s| s.capitalize}.join(" ") does not work because #capitalize does not modify the original; it gives you a copy. Map/collect really collects these copies, #each does not. However "I love guitar playing".split.each{|s| s.capitalize!}.join(" ") Does work, because the self-modifying #capitalize! is available. Personally I'm starting to prefer #map , also because of this: a = (1..9).map{|n| n*n} #versus my old way a = [] #annoying (1..9).each{|n| a<