Ruby/Loops

From Meshplex

Jump to: navigation, search
Image:Ruby_on_rails_tutorials.jpg
Ruby for complete beginners
Ruby Introduction
What can I use RoR for?
Reasons for choosing RoR over other popular programming languages such as php or asp.net .What makes Ruby so much more special
Where can I find RoR? In what “forms” does it come?
How to install RoR.Solutions for both the novice and professional programmers on Windows,Mac OS X and Linux.Prerequisites.
Ruby programming tutorials for beginners:
Ruby Basics
Ruby Variables, Datatypes, Operators
Ruby Symbols
Ruby Statements
Ruby Converting data to another type: type conversion or typecasting
Ruby Arrays, Hashes, Ranges
Ruby Functions and built in functions
Ruby Control structures
Ruby Regular expressions and blocks
Ruby Loops
Ruby Recursion
Ruby Data Structures
Ruby Methods, Classes, Modules, Namespaces
Ruby Exceptions
Ruby Object Oriented Programming
Ruby Multithreading
Ruby File Handling.Input and Output
Ruby Basic GUI
Ruby and databases.Ruby on Rails and MySQL
Ruby Basic CGI.Using fastCGI
Ruby Basic Networking and web programming
Ruby Basic Graphics
Ajax and Rails.Web 2.0 and what it means
Ruby Testing, Debugging, Automation of tasks
Ruby Apache,Capistrano, Mongrel,lighttpd – reviews and tips
Finding a Ruby on Rails ready web hosting company
BONUS: mini tutorial for a simple RoR application

[edit] Ruby Loops

You use loops whenever you need the program to repeat some instructions without you having to write the instructions for each time you need them to repeat.Let's say you need to count how many words are in a text file. You do this using a loop of code among other instructions, reading from the file and incrementing a counter with 1 each time a new word is read, until you reach the end of file marked by EOF.

The While loop

Code example:

i = 0
while not_eof
puts  "#{i} words in file.\n"
i += 1
end

This code will roughly read a file in theory until it reaches the end and count the words. Notice I did not write any specific code regarding how to actually read from the file or detect the eof because it's beyond the purpose of this part of the tutorial.

If you need something that you can test immediately all by yourselves:

i = 0
while i < 10
puts "hello \n"
i += 1
end

This will print "hello" 10 times on the screen.


The Until loop

Works similarly to the while loop.

Example:

i = 0
until i == 10
puts "hello \n"
i += 1
end

The For loop

A for loop will go through every item in a given set:

for value in 1..10
    puts "hello #{value.to_s} times"
end

Image:For.gif

Something similar can also be done in a much more simple way like this : ( using the .times method)

10.times do
         puts "hello"
end
Previous Next
Personal tools