Page 1 of 1

Ruby: Using Loops

#1 erik.price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 485
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Posted 15 January 2010 - 03:55 PM

Hi everyone, this will be a fairly brief (but hopefully informative ;)) tutorial on looping statements in Ruby. If you want, you can check out kingbradley6's Ruby Basics first.

Although iterators and blocks are technically loops as well, this tutorial will not cover them, as EdwinNameless' excellent Blocks and Iterators Tutorial is already available.

Ruby has three main looping statements:
  • while
  • until
  • for
while

Most languages have some sort of while statement, and Ruby's acts quite similar to the while loop in Java and C.

In Java, you could have a while loop like this to count to 10:
int i = 1;
while(i <= 10)
{
	System.out.println(i++);
}



Similarly, in Ruby, the same could be accomplished with:
i = 1
while(i <= 10) 	#note that the parenthesis are not required:
				#while i <= 10 is also acceptable
  puts i
  i = i.succ
end



The 'do' keyword is optional and can be used like this for clarity:
while x != 2 do
	#something
end




While loops will continue iterating until the condition (statement after keyword 'while', which in this case is 'i <= 10') becomes false (or nil). An important thing to remember here is that all values in Ruby are true, except false and nil.

The boolean condition is not limited to x > y obviously, you can use any boolean expression there.

while Loop as a Modifier
Ruby's elegant syntax allows for compact forms of the while loop. For instance, the code from before to count to 10 could be written like this:
x = 0
puts x = x + 1 while x < 10


This is very similar to the if modifier, and although it may appear similar to a do/while loop in other languages (meaning the body of the loop is executed at least once before the expression is checked), the condition here is actually checked before anything is printed.
To demonstrate this:
puts "Will I be printed?" while false
#nothing is printed because 'false' evaluates to, well, false :p



until
The 'until' loop is pretty unique for programming languages; it basically means 'while not' and is purely syntactic sugar for the language. Basically what it does is allows you to write more clear, and human readable code.

Here's an example:
i = 0
while not i > 10 do
	  puts i
	  i += 1
end


Yes, it's extremely contrived, but it gets the point across. You have to stop and think for a minute about while not i > 10 to see what it is doing.

The until loop makes this example code much more readable:
i = 0
until i > 10 do
	  puts i
	  i += 1
end


Doesn't that read better?

Fun fact: until not i < 10 is the same as while i < 10 and until not not i > 10 is identical to until i > 10 And so on :D

until Loop as a Modifier

Just like with the while loop, the until loop can be used to write a compact, but equivalent loop.
x = 0
puts x = x + 1 until x > 10

Just as before, this behaves not like a do/while, but a while loop.

for
The for loop in Ruby is unlike that of C based languages, and is more like Python's. Officially, the loop is called 'the for/in loop', but for loop works too.

The syntax for this loop goes like this:
for variable in collection do #again, do is optional
	loop body
end



'variable' can be either a single variable, or a comma separated list of variables (which you would use with hashes, for example). 'collection' is any object with an each iterator (for example, ranges, arrays, strings, hashes, etc.)

Here's an example for/in loop to count, as before, from 1 to 10.
range = 1..10
for i in range do
	puts i
end


Here's an example with multiple variables:
hash = {:a => 1, :b => 2, :c => 3}
for key, value in hash
	puts "#{key} => #{value}"
end



The for loop can be rewritten using the each method. For example, this next section is identical to the first foor loop example. (see Blocks and Iterators Tutorial if you're confused about this)
range = 1..10
range.each do |i|
	puts i
end


Unlike both until and while loops, for/in cannot be written as a modifier statement.

Faking a Do/While Loop
If you absolutely must have a do/while loop in your program, you can manipulate Ruby's syntax to your advantage. (however be warned: future versions of Ruby may not support this syntax)

begin
	puts "I was printed!"
end while false



Even though the while loop evaluates to false, it will still print "I was printed" before exiting the loop.

However, as I said before, this might not be supported in later versions of Ruby, and there are always ways around doing this.


That about wraps this tutorial up. I hope you've enjoyed it :)

Is This A Good Question/Topic? 3
  • +

Replies To: Ruby: Using Loops

#2 ladyinblack  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 9
  • View blog
  • Posts: 419
  • Joined: 08-April 09

Posted 16 March 2010 - 06:37 AM

Nice tutorial. It motivated me to play around with other functions.

Ronica
Was This Post Helpful? 0
  • +
  • -

#3 Redalin  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 23
  • Joined: 02-October 11

Posted 05 October 2011 - 08:26 PM

Great tutorial, I am having some trouble with loops and this will help me a lot! :red_indian:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1