From: "Christopher Özbek" Date: 2002-03-27T06:07:45+09:00 Subject: Re: yield in iterator's body - > > This ... > > ["H", "A", "L"].collect { |x| x.succ }.each{|b| > puts "I got #{b}" > } > > .. produces > > I got I > I got B > I got M Collect changes an array by replacing each entry by the result of the code block and returns this new array (collect! changes inplace). So ["H", "A", "L"].collect { |x| x.succ } returns ["I", "B", "M"] > However, this ... > > ["H", "A", "L"].each { |x| x.succ }.each{|b| > puts "I got #{b}" > } > > . gives: > > I got H > I got A > I got L > > So, my question is, what exactly is the difference between 'each' and > 'collect'? each just executes the code block for each element once. Neither is the array changed (collect!) nor is a new one returned (collect). > Why doesn't the 'each' block return the value of the last expression? The value of the last expression would be "M" in this case, would it? I don't know, this is maybe just because in most cases the programmer needs the array more than the result from the last call. Christopher :)