Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Loops Ruby Loops The Until Loop

Connor McKelvey
Connor McKelvey
6,200 Points

Single Line While Loop with Brackets

Hello, Jason mentioned that it is common for ruby developers to use curly brackets {} when using certain loops when you want it all on a single line. He also said that you can omit the do when using a while or until loop.

However it doesnt seem to work with while loops.

I have tried the following:

 i = 0;
 while i < 10 { i += 1 }
 puts i

and

 i = 0;
 while (i < 10) { i += 1 }
 puts i

And i get the following error:

test.rb:2: syntax error, unexpected '{', expecting keyword_do_cond or ';' or '\n'
while (i < 10) { i += 1 }
                ^
test.rb:2: syntax error, unexpected '}', expecting end-of-input

Seems like this should be possible to do. Anyone know how to do a single line while loop?

1 Answer

Rachelle Wood
Rachelle Wood
15,362 Points

Hi,

To use a while loop on one line, you have to do the following:

i = 0
puts i += 1 while i < 10