On 5/21/07, Hakusa / gmail.com <Hakusa / gmail.com> wrote: > I have some good experience in other languages and consider myself a > good programmer, but some of the good techniques I've picked up don't > seem to work here. Here are two examples. > > x=aNum > y=0 > x.times do > (y+1).times do > Stuff > end > end > > y never actually increments. Why? (No pun intended.) y should go up > one x times by the end. Instead it stays at zero. And it's kind of > troubling that is does the loop once even when y is zero; or is that > just because it's a 'do' loop and not a 'for' loop? > > > And I've learned that to do the gets thing, I have to have > STDOUT.flush before it. It seems that no matter what I do, if it's > even two lines above the gets, I get the gets at the start of the > program even though it was towards the end. Why? If it is such a > common thing, why is STDOUT.flush not automatically called by the > language? > > > Although as much as this all complexes me, I am very glad to be able > to do this with guilty glee: > > STDOUT.flush > puts 'Hello ' + gets.chomp > > Although I have a feeling I'll rarely get to use this trick. > > > I can't answer the STDOUT.flush question because I've never had to use it, but the lines > x=aNum > y=0 > x.times do > (y+1).times do > Stuff > end > end doesn't change x or y. If aNum = 5, for example, the code above would interpret as: 5.times do 1.times do Stuff end end You would do Stuff 5 times with x as 5, y as 0 and (y+1) as 1. If you just want to have a value increment: aNum.times do |i| puts i end Note the |i| after do. This prints 0 1 2 3 4 #times isn't clear that it starts at zero from looking at it, so you can also write: 0.upto(aNum - 1) do |i| puts i end Or even (0..4).each do |i| puts i end A nested loop: aNum.times do |i| aNum.times do |j| puts "i:#{i} j#{j}" end end Todd