New to Ruby - While loop issues in IRB
So a few days ago I decided I would try and learn Ruby and it's actually been going pretty well. I've been mostly fiddling around in IRB until I can find a non-trivial program to code to test my knowledge.
However, today I ran into 开发者_如何学编程an unexpected issue with a While loop and I was hoping y'all could help me out with this:
irb(main):001:0> i = 0
=> 0
irb(main):002:0> while (i < 1000)
irb(main):003:1> i++
irb(main):004:1* end
SyntaxError: (irb):4: syntax error, unexpected keyword_end
from C:/WINDOWS/Ruby/bin/irb:12:in `<main>'
Why exactly isn't this working as I'm expecting it to? According to this site I have the structure correct, so what am I missing here?
I'm running Ruby 1.9.2 under Windows XP, if that's of any help.
i++
is not valid ruby. You need to do i += 1
.
Edit: See Mladen's comment as to what the parser is seeing.
Unless your purpose is specifically to understand how while loops and integer addition/comparison work, what you really want is
1000.times do |i|
end
Ruby doesn't have C-style increment (++
) or decrement (--
) operators. You want this:
i = 0
while(i < 1000)
i = i + 1 # Or i += 1
end
精彩评论