The Ruby Programming Language

Loops

6.times do
  puts "Hi" #writes it 6 times.
end

#prints a b c d each on a new line
['a', 'b', 'c', 'd'].each do |i|
  puts i 
end

#the same
for i in ['a', 'b', 'c', 'd']
    puts i 
end


#This is how we get input from user
while line = gets
 # do stuff
end

file = File.open("filename")
while line = file.gets
 # do stuff
  break #goes to first line after loop
  redo  #repeats loop at the current iteration
  next  #skips to next iteration
  retry #restarts loop from first iteration
end


#Mostly, use the class's iterators: each

José M. Vidal .

3 of 11