"ts" <decoux / moulon.inra.fr> schrieb im Newsbeitrag news:200312151626.hBFGQV102470 / moulon.inra.fr... > >>>>> "J" == JB <temuphaey0 / jetable.net> writes: > > J> for i in 1..3 > J> threads << Thread.new(i) { |i| > [...] > J> I expected to see: 123 > J> but I got : 333 > > J> Is it a bug? or is it normal? > > it's normal : the 3 threads share the same variable `i' and this is the > varible in `for' > > J> Upon to me the 'i' variable of the 'print i' should be '|i|' (which is the > J> last declaration of 'i') and not the 'i' in 'for i in 1..3' (which value is > J> '3' and the end of the loop). > > wait for ruby 2 There's another easy fix: change the name of the variable you use inside the block. The original version was effectively equivalent to this: threads = [] for i in 1..3 threads << Thread.new { sleep(i) print i } end threads.each { |aThread| aThread.join } Now the meaning of the Thread constructor args becomes visible: threads = [] for i in 1..3 threads << Thread.new(i) { |j| sleep(j) print j } end threads.each { |aThread| aThread.join } Will print the expected "123". Kind regards robert