Patterns with loops
Long before screens could show pictures, programmers drew with letters: trees, rockets, whole portraits made of # and *. All you need is one trick – in Ruby, a string times a number repeats the string:
puts "-" * 20
puts "bacon " * 3
"🥓" * 5Put that into a loop and let the number grow by one on every pass, and you get a staircase. 1.upto(5) counts from 1 to 5, and every pass draws one row – exactly as many # as the row's number:
1.upto(5) do |row|
puts "#" * row
endA pyramid needs room on the left, too. Count what each row needs: in a pyramid five rows high, row 1 has 4 spaces and 1 star, row 2 has 3 spaces and 3 stars … So row n has 5 - n spaces and 2 · n - 1 stars. Press ⏯ Step through and watch both numbers change:
height = 5
1.upto(height) do |row|
spaces = " " * (height - row)
stars = "*" * (2 * row - 1)
puts spaces + stars
endRuby can do the counting of spaces for you: center(width) pads a string on both sides until it is that wide. 1.step(11, 2) counts 1, 3, 5 … 11 – the branches of a tree, with a trunk at the end:
width = 11
1.step(width, 2) do |n|
branch = "*" * n
puts branch.center(width)
end
puts "|".center(width)Two loops inside each other make a grid: the outer one goes through the rows, the inner one through the columns of each row. For the chessboard a square is dark when row + column is even. The ? and : are a short if: condition ? this : that.
8.times do |row|
line = ""
8.times do |col|
line += (row + col).even? ? "# " : ". "
end
puts line
endThe same grid with a different rule draws whatever you can compute. Here a square gets an X when it lies on one of the two diagonals:
size = 9
size.times do |row|
line = ""
size.times do |col|
on_diagonal = col == row || col == size - 1 - row
line += on_diagonal ? "X" : "."
end
puts line
endChange the rule and see what comes out: row == 4 || col == 4 is a plus sign, row == col one diagonal, (row * col) % 3 == 0 a pattern you have to see for yourself. In lesson 33 Chunky draws real lines instead of letters.
#, the next four, and so on, down to a single #. Use a loop – not five puts written by hand.# a staircase going down: 5 #, then 4, 3, 2, 1
# a diamond, 7 wide: rows of 1, 3, 5, 7, 5, 3, 1 stars, centered