OneBite.Dev - Coding blog in a bite size

implement a three nested loop in Ruby

Code snippet on how to implement a three nested loop in Ruby

  for i in 1..3 do
    for j in 1..3 do
      for k in 1..3 do
        puts "i = #{i}, j = #{j}, k = #{k}"
      end
    end
  end

This code snippet uses three nested for loops to print out all possible combinations of the numbers 1, 2 and 3. The outermost loop “for i in 1..3 do” iterates through 1, 2 and 3. On each iteration, the middle loop “for j in 1..3 do” is also iterated through 1, 2 and 3. Finally, the innermost loop “for k in 1..3 do” is iterated through 1, 2 and 3. For each iteration of the nested loop, the code prints out the number values of i, j and k. This output is done using the puts statement, which prints out the string “i = #{i}, j = #{j}, k = #{k}” while dynamically replacing #{i}, #{j} and #{k} with the corresponding value. So, the output of the code will be nine lines of numbers, each line following the pattern “i = NUMBER, j = NUMBER, k = NUMBER” for every combination of 1, 2 and 3.

ruby