|
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
Something similar can also be done in a much more simple way like this : ( using the .times method)
10.times do
puts "hello"
end
|