Ruby Programming Exercises #1: Printing out Shapes
Excerpt from my book Learn Ruby Programming by Examples
This article is an adapted version of the exercises in the first chapter of the book: Learn Ruby Programming By Examples.
Printing out asterisk characters (*) in shapes is often used as beginner’s programming exercises, as they are simple, easy to understand, and visually interesting.
You can install Ruby, edit in your favourite editor and run from the command line. Or, try online Ruby sites, where you can write and run code in your browser.
Zhimin’s notes: While the solutions are shown in Ruby language, the thinking process and solution design are applicable to all programming languages. For example, I had another book “Learn Swift Programming by Examples” for similar set of exercises.
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
· Zhimin’s Notes
Ex 1: Print a Triangle
Write a program to print out asterisks in the triangle shape below:
*
**
***
****
*****
The naive solution is to print each line manually. In Ruby, you can print a newline with puts
.
puts '*'
puts '**'
...
But we can do better!
Noticing that row 1 has 1 asterisk, row 2 has 2 asterisks, row 3 has 3 asterisks, etc. We can use this pattern to create triangles of any size.
Here are some tips to help along the way:
Tip 1: Printing the same character multiple times
To generate multiple occurrences of the same character, use the multiply symbol *
. e.g. 'X' * 3
will output XXX
.
Tip 2: Defining a variable
In Ruby, defining variables is as easy as:
star_count = 2
puts '*' * star_count # => **star_count = star_count + 2 # now star_count = 3
puts '*' * star_count # => ***
Tip 3: Loop a fixed number of times
3.times do
puts "Hello!"
end
The above segment loops over the contents between do
… end
3 times. i.e. the output will be:
Hello!
Hello!
Hello!
Now, have a go at printing the triangle yourself before scrolling down to see the solutions :)
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:
*
**
***
****
*****
****
***
**
*
Now we aren’t always incrementing star_count
; from the middle row we need to start decrementing it.
Tip 4: Control flows using if
… else
We can add control flow using if
…else
to run different code statements.
For instance, let’s take simple grades program:
score = 75
if score >= 60 # greater than or equal to 60
puts "Passed!"
else # when score is less than 60
puts "Failed"
end
The output of this program is Passed!
.
Now have a go extending “Print a Triangle” to “Print a Half-Diamond”, my solution will be at the bottom of this article.
Ex 3: Print a Diamond
This is an extension to Ex02: to print 7 rows of a full diamond instead of a half.
*
***
*****
*******
*****
***
*
This time, you will need to consider both the number of spaces and the number of stars. The tricky part is finding the pattern. However, if you can complete the previous two parts, then you know everything you need to print a diamond.
Challenges
Challenge yourself by printing different shapes like the below ones.
Rhombus
*****
*****
*****
*****
*****
Hollow Square
*****
* *
* *
* *
*****
Heart
***** *****
******* *******
********* *********
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
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
endcount = 10
8.times do
count = count - 1
stars = "*" * count
puts stars
end
2. Use control flow with if
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
For solutions to the challenges, check out the book’s solutions section.
Zhimin’s Notes
The “Learn Ruby Programming by Examples” ebook is based on teaching material I prepared to teach my daughter programming when she was 13-year old. Later, she participated in book editing and illustrations.
My daughter now works at one of FAANG companies.
A typical how-to-program book will go through the programming concepts and syntax, followed by demonstrations with simple examples. I have read dozens of them (for different programming languages or tools) before, and have taught this way at universities. In my opinion, it was not an effective approach. It is more like a teacher dumping knowledge upon students. But I did not know a better way until I discovered The Michel Thomas Method.
The Michel Thomas Method is developed by Michel Thomas for teaching foreign languages. Thomas claimed that his students could “achieve in three days what is not achieved in two to three years at any college”. My understanding of this method is that the teacher starts with a simple conversation scenario, and then gradually expands the scenario with a few new words each time. That way, students are familiar with the conversation topic and the majority of words or sentences, while learning some new in conversations.
I believe this teaching method can be applied to programming. Not only a programming language may also be considered as ‘a language’, but also very practical. The ‘conversation’ in speaking languages is coding exercises in programming. People learn better when they get satisfaction or feedback (see their programs running).
Thinking in programming is much more important than being familiar with a programming language. There is no better way to learn than by coding practical exercises. In this book, I have chosen exercises that are very simple to understand, besides teaching values, they are useful and fun to do.
Quite often, new-to-automation testers asked me to recommend programming books. I told them: “My daughter started writing raw Selenium tests in Ruby at the age of 12. Then she learned programming with this book”.