Ruby Programming Exercises #1: Printing out Shapes

Excerpt from my book Learn Ruby Programming by Examples

Table of Contents:
· Ex 1: Print a Triangle
· Ex 2: Print a Half-Diamond
· Ex 3: Print a Diamond
· Challenges
· Solutions
Ex 1: Print a Triangle
Ex 2: Print a Half Diamond
Ex 3: Print a Diamond

Ex 1: Print a Triangle

Write a program to print out asterisks in the triangle shape below:

*
**
***
****
*****
puts '*'
puts '**'
...
star_count = 2
puts '*' * star_count # => **
star_count = star_count + 2 # now star_count = 3
puts '*' * star_count # => ***
3.times do
puts "Hello!"
end
Hello!
Hello!
Hello!

Ex 2: Print a Half-Diamond

In the first exercise, we printed a triangle. Now, let’s extend that further into a half-diamond shape:

*
**
***
****
*****
****
***
**
*
score = 75
if score >= 60 # greater than or equal to 60
puts "Passed!"
else # when score is less than 60
puts "Failed"
end

Ex 3: Print a Diamond

This is an extension to Ex02: to print 7 rows of a full diamond instead of a half.

*
***
*****
*******
*****
***
*

Challenges

Challenge yourself by printing different shapes like the below ones.

*****
*****
*****
*****
*****
*****
* *
* *
* *
*****
*****     *****
******* *******
********* *********
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*

Solutions

Ex 1: Print a Triangle

count = 0
10.times do
count = count + 1
stars = "*" * count
puts stars
end

Ex 2: Print a Half Diamond

There are two alternative approaches to this problem.

  1. Reuse the solution to Part 1 twice, but count decreases in the second loop.
count = 0
8.times do
count = count + 1
stars = "*" * count
puts stars
end
count = 10
8.times do
count = count - 1
stars = "*" * count
puts stars
end
15.times do |row|
# row starting with 0
if row < 8
star_count = row + 1
else
star_count = (15 - row)
end
puts '*' * star_count
end

Ex 3: Print a Diamond

15.times do |row|
if row < 8
star_count = row * 2 + 1
space_count = 8 - row
else
star_count = (15 - row) * 2 - 1
space_count = row - 6
end
puts ' ' * space_count + '*' * star_count
end

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store