Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Ruby Programming
Previous Page Home Next Page

Loops

Don't tell anyone, but Ruby has pretty primitive built-in looping constructs.

The while loop executes its body zero or more times as long as its condition is true. For example, this common idiom reads until the input is exhausted.

while gets
  # ...
end

There's also a negated form that executes the body until the condition becomes true.

until playList.duration > 60
  playList.add(songList.pop)
end

As with if and unless, both of the loops can also be used as statement modifiers.

a *= 2 while a < 100
a -= 10 until a < 100

On page 78 in the section on boolean expressions, we said that a range can be used as a kind of flip-flop, returning true when some event happens and then staying true until a second event occurs. This facility is normally used within loops. In the example that follows, we read a text file containing the first ten ordinal numbers (``first,'' ``second,'' and so on) but only print the lines starting with the one that matches ``third'' and ending with the one that matches ``fifth.''

file = File.open("ordinal")
while file.gets
  print  if /third/ .. /fifth/
end
produces:
third
fourth
fifth

The elements of a range used in a boolean expression can themselves be expressions. These are evaluated each time the overall boolean expression is evaluated. For example, the following code uses the fact that the variable $. contains the current input line number to display line numbers one through three and those between a match of /eig/ and /nin/.

file = File.open("ordinal")
while file.gets
  print if ($. == 1) || /eig/ .. ($. == 3) || /nin/
end
produces:
first
second
third
eighth
ninth

There's one wrinkle when while and until are used as statement modifiers. If the statement they are modifying is a begin/end block, the code in the block will always execute at least one time, regardless of the value of the boolean expression.

print "Hello\n" while false
begin
  print "Goodbye\n"
end while false
produces:
Goodbye
Ruby Programming
Previous Page Home Next Page

 
 
  Published under the terms of the Open Publication License Design by Interspire