From: Robert Klemme Date: 2005-02-28T05:44:59+09:00 Subject: Re: for vs. each "Fear Dubh" schrieb im Newsbeitrag news:cvt8g2$g47$1@reader01.news.esat.net... > Hi, > > "Robert Klemme" wrote in message > news:38ea7eF5o769pU1@individual.net... >> >> "Fear Dubh" schrieb im Newsbeitrag >> news:cvslbj$9ns$1@reader01.news.esat.net... >> > >> > "ts" wrote in message >> > news:200502271128.j1RBSA019680@moulon.inra.fr... >> >> >>>>> "F" == Fear Dubh writes: >> >> >> >> F> Is there a difference between: >> >> F> for foo in bar do ... >> >> F> and >> >> F> bar.each do |foo| ... >> >> >> >> uln% ruby -e 'for a in [12] do end; p a' >> >> 12 >> >> uln% >> >> >> >> uln% ruby -e '[12].each do |a| end; p a' >> >> -e:1: undefined local variable or method `a' for main:Object > (NameError) >> >> uln% >> >> >> >> >> > Thanks! >> > >> > Does each have a fatter frame then? >> > Is "for ... in ... do ..." more efficient? >> >> I would believe not, but you can test this yourself (hint "ruby -r > profile" >> and module Benchmark). >> >> Indenpendently of that I strongly recommend the usage of "each" as it is >> used 99% of the cases and it's simply standard. Although it's not an >> enforced convention, people will expect that and it makes everybody's >> life >> easier to stick to some conventions. >> > OK, Thanks, > > Now I feel like a bold child, scolded for stuffing my face > with this delicious syntax sugar! :-) LOL > I have a further question: > As ts showed "for ... in ... do" is not exactly the same as "... each do > ...", > so is there an "un-sugared" expression that is equivalent to "for ..."? Probably this: x = nil enum.each {|x| ...} # x carries the last value here > Is there any circumstance where it would be better to use "for"? Frankly speaking, I can't remember having felt the need for "for". But you can argue that it looks better for numeric ranges: $ ruby -e 'for i in 1..5 do puts i end; puts i' 1 2 3 4 5 5 Robert@Babelfish2 ~ $ ruby -e 'i=nil; (1..5).each{|i| puts i}; puts i' 1 2 3 4 5 5 To be honest, I've completely forgotton "for .. in" and I use #each even for numeric ranges - in spite of the uglyness. :-) Btw, there's also #upto, #downto and #step: $ ruby -e '1.step(10,2){|i| puts i}' 1 3 5 7 9 Robert@Babelfish2 ~ $ ruby -e '1.upto(5){|i| puts i}' 1 2 3 4 5 Robert@Babelfish2 ~ $ ruby -e '5.downto(1){|i| puts i}' 5 4 3 2 1 Kind regards robert