Cycles in Ruby

Loops are fundamental tools in Ruby to repeat the execution of a block of code as many times as necessary. There are different types of cycles to adapt to different needs.

while: Link to heading

  • Used to execute a block of code as long as a condition is true.
  • The condition is evaluated at the beginning of each iteration.
  • If the condition is true, the code block is executed and the condition is evaluated again.
  • If the condition is false, the loop ends.

Example: Link to heading

x = 1

while x < 5 do
    puts "hello #{x}"
    x += 1
end

until: Link to heading

  • It is similar to while, but executes the code block as long as a condition is false.
  • It can be useful for writing more intuitive code.

Example: Link to heading

x = 1

until x >= 5 do
    puts "hello #{x}"
    x += 1
end

for: Link to heading

  • Used to execute a block of code once for each element in a sequence.
  • The sequence can be a range of numbers, an array or any other iterable collection.

Example: Link to heading

for i in 1..4 do
    puts "hello #{i}"
end

each: Link to heading

  • It is similar to for, but also provides access to the current element of the sequence.
  • It can be useful to perform operations on each element of the sequence.

Example: Link to heading

[1, 2, 3, 4].each do |x|
    puts "hello #{x}"
end

times: Link to heading

  • Used to execute a block of code a specific number of times.
  • Can be useful for repetitive tasks that must be executed a certain number of times.

Example: Link to heading

4.times do |x|
    puts "hello #{x}"
end

Additional keywords: Link to heading

  • break: Ends the innermost cycle.
  • next: Jump to the next iteration of the innermost loop.
  • redo: Restarts this iteration of the innermost loop, without checking the loop condition.
  • retry: The section of the code that was rescued is executed again.

In short, loops allow you to execute a block of code repetitively, adapting to different needs. It is important to choose the appropriate cycle for each case and use the additional keywords to control the flow of the cycle.

Keep learning about cycles to create more efficient and reusable programs!

Additional Tips: Link to heading

  • You can use loop nesting to execute code inside another loop.
  • You can use the && operator to combine two conditions in the loop condition.
  • You can use the break method to exit a loop at any time.

Example: Link to heading

for i in 1..10 do
    for j in 1..10 do
        break if i == j
        puts "#{i}, #{j}"
    end
end

Keep experimenting with loops to create more complex and powerful programs!

<< Conditionals in Ruby Ranges in Ruby >>