Ruby Programming Basics Part 1: Expressions, Strings, Numbers, If/Else, Loops
In this learning group, our focus will be on Ruby on Rails.
Ruby on Rails (or Rails in short) is a framework based on Ruby programming language.
You cannot learn Rails without knowing basic Ruby. In this 3-part guide, I will share what do you need to know about Ruby programming.
In this part, I will talk about:
- Setting up your environment
- Expressions
- Strings
- Input and Output
- Conditionals
- Loops
Setting Up Your Environment
To start, you need to have Ruby installed in your computer. The instructions are as follows:
https://www.ruby-lang.org/en/documentation/installation/
For demonstration purposes, I will be using Cloud9. Start an empty workspace. Ruby is already installed in the workspace.
You do not have to install the latest version of Ruby. As long as the version is higher than 2.0, it will be fine.
Using irb
You can start running Ruby code using a program call irb (for Interactive Ruby). The irb shell will evaluate the Ruby expressions you type, and show you the results.
When you are developing your Rails application, using irb is a great way to test out a new concept.
To use irb, type irb
in your bash:
You should see the prompt changed. From here, you can type in any Ruby expressions you want. The program will evaluate it and return you the results.
For example, I type in some basic arithmetic operations:
When you are done with irb, type exit
at the prompt. Then you will return to your bash.
Expressions
An expression is a statement that the programming language interprets. Once the interpretation is done, the program will produce another value.
You have seen examples of expressions earlier:
4 + 5
78 * 2
90 / 3
These are examples of expressions. Ruby interprets the expression 4 + 5
, and return the result 9
.
Basic Math Operations and Comparisons
You have seen that Ruby can perform arithmetic operations. The math operators are the same as other languages:
+
for addition-
for subtraction*
for multiplication/
for division**
for exponentiation
You can also compare 2 values and Ruby will return either a true
or false
. The operators are:
<
for less than<=
for less than or equal>
for greater than>
for greater than or equal==
for equal (note that there are 2 equal signs)!=
for not equal
Strings expressions
A string is a series of text characters. We can use strings to hold information such as name, email address, etc.
You can use double quotes (“
) or single quotes (‘
) to specify a string:
You can combine the strings together with a “+
” operator:
Remember, when you see a double quotes or single quotes, it is a string. Even when what you see is a number. For example:
“3”
This is a string
3
This is a number
Comment
Ruby will ignore everything after a hash mark (#
) until the end of the line. Developers use this as a comment.
Variables
Like all other programming languages, you can create variables in Ruby. Variables are temporary containers that save a certain values. You can then extract these values later on.
You do not have to declare the variables. Assigning them create the variable. You use the =
operator to assign variables. Here are some examples:
Unlike other programming languages, variables don’t have types in Ruby. They can hold any values you want.
You can also use the +=
operator to add on to the existing value of a variable:
The use of variables is important when coding. As much as possible, assign values to variables. There are some conventions when naming variable names:
- Variable names should be descriptive. This means when someone look at the code, they should know what type of data the variable contains. You will learn more about this when you are developing Rails application.
- Use all lower case letters. Avoid numbers. And separate words with underscores. E.g. “
my_variable
” instead of “myVariable
”. This style is called “snake case”.
Input and Output
A simple program you can write is a meet and greet. How this works is very simple. When you start your program:
- The program will first ask you for your name.
- You will then enter your name.
- Then the program will greet you by your name.
Let’s see how to do this program.
First, we create a file call “greet.rb
”. The “rb
” extension is for files written in Ruby programming language.
Then we type the following into the file.
print “Welcome to Meet-and-Greet. May I have your name please?”
name = gets
puts “Hello, “ + name
Unlike running your code in IRB, this time round, you type your code in a file. Then you use your terminal to run this file using the following command:
ruby greet.rb
Make sure that you are in the directory where the file located. In this case, I created the file in the root workspace folder. To check, you can use the ls
command to check the files in current directory.
At this stage, you have created a very simple Ruby program. Let’s run this program.
Type in your name and you will get the final output greeting.
Let’s take a look at what’s going on here.
print
, puts
, gets
are methods. Methods are code where you can execute on demand. You will learn more about methods in Part 2.
In the first line, we use the print
method to “print” that string of text in the console. We need that line to ask for the name of the user.
In the second line, we ask the user for his input and save it into a variable name
. We do this by using the the method gets
. The gets
method read what the user type in the terminal.
At this point of time, the program stopped because it is waiting for the user to type something.
Lastly, the program “puts” the string back to the console. Why use puts
instead of print
? There is one subtle difference. puts
return a new line character whereas print
doesn’t.
In Ruby, we use puts
more often than we use print
.
Note: puts
is a simple but useful method that programmers use to debug their Rails program.
Strings
String Interpolation
You have learnt that you can combine strings like this:
puts “hello “ + “world”
=> “hello world”
You can also save the string into a variable, and combine them with another string:
name = “Thiam Hock”
puts “hello “ + name
=> “hello Thiam Hock”
Notice that I did not use quotation for name
.
If you want to combine a huge number of strings together, this can get pretty messy. So Ruby offer a cleaner solution known as String interpolation.
Let’s see how it works first:
name = “Thiam Hock”
puts “Hello #{name}”
=> “hello Thiam Hock”
Whenever you include #{ … }
inside a string with double quotation, Ruby will treat the value in the curly braces as an expression. This means that Ruby will evaluate the expression and return a value.
In this case, Ruby evaluate the variable name
and return the value “Thiam Hock”
into the string.
Most Ruby programmers use string interpolation instead of combining them using the +
operator.
Converting to other Data Types
You can convert strings to other data types such as numbers. For example:
num = “3” # this is a string
puts num.to_i # convert to integer
=> 3 # this is an integer
puts num.to_f # convert to float
=> 3.0 # this is a decimal
Converting to Strings
You can also convert other data types to strings using the `to_s` method. For example:
num = 3 # this is an integer
puts num.to_s
=> “3” # This is a string
Conditionals
Sometimes you do not want the program to evaluate every expression. You only want the program to evaluate them if certain conditions exist.
In this case, you can use conditional statements.
If a condition is met, Ruby will evaluate the expression. If it is not met, then Ruby will skip it. A simple example will be:
if 10 > 5
puts “of course 10 is more than 5”
end
Like most other languages, you can also have multiple branches in the condition.
num = 10
if num > 5
puts “#{num} is definitely more than 5”
elsif num < 5
puts “#{num} is definitely less than 5”
else
puts “#{num} is equal to 5”
end
The above conditional statement works as follows:
- Ruby first evaluate whether is
num
more than5
. If the answer is yes, then Ruby will executeputs “#{num} is definitely more than 5”
, then skip the rest. - If
num
is not more than 5, Ruby will then check ifnum
is less than5
. If the answer is yes, then Ruby will executeputs “#{num} is definitely less than 5”
, and skip the rest. - If
num
is also not less than5
, Ruby will execute the last statement underelse
, which isputs “#{num} is equal to 5”
.
There is no limit to how many elsif
you want.
Notice that conditionals rely on boolean expression (one that only return true
or false
) to decide which code to execute. Examples are num > 5
and num < 5
.
If you only have one statement, you can also do this:
puts “#{num} is definitely more than 5” if num > 5
Optional:
Ruby allow conditional statements in the format of ternary operator if the expression is only one statement:
if <boolean expressions>
<expression to execute if true>
else
<expression to execute if false>
end
is equal to
<boolean expression> ? <expression to execute if true> : <expression to execute if false>
Ternary operator will make your code shorter.
Unless
The opposite of if
is unless
. Sometimes you want to negate your conditionals like this:
if ! num > 5
puts “#{num} is not more than 5”
end
It can get a little bit hard to read. So you can do use `unless`:
unless num > 5
puts “#{num} is not more than 5”
end
You can read the conditional like: “Unless num is more than 5, do not execute puts “#{num} is not more than 5”
.
If you are not comfortable with unless
, please feel free to continue using if
.
Loops
Sometimes we want to execute an expression more than once. We can do something like this:
puts “I want to execute this statement”
puts “I want to execute this statement”
puts “I want to execute this statement”
puts “I want to execute this statement”
Doing multiple executions this way presents 2 problems:
- You need to know in advance how many times you want to execute the expression. There are times where you do not know this information in advance.
- What if you want to change the expression? Then you will have to change it 4 times (or possibly more).
Besides the above 2 problems, you are not making full use of what computers are good for:
Repeat the executions of the same command.
We can use loop to execute code repeatedly. There are 2 types of loops: while
loop and for
loop.
While Loop
A while
loop consists of the word while
, a boolean expression (just like in if
statement), the code you want to repeat, and the word end
.
For example:
num = 1
while num <= 5
puts “I execute this statement #{num} times”
num += 1
end
The first expression num = 1
create a variable call num
and assign the integer 1
to num
.
The second expression is the start of the while
loop. After the while
keyword, there is a boolean expression which evaluates to either true
or false
. While the boolean expression is true, the loop will execute the expressions within the loop.
The third expression is the code I want the loop to execute.
The fourth expression is to increment the num
variable. So after the third expression is executed, num
will be incremented by 1
. We need to do this so that we will not execute the third expression forever.
The keyword end
marks the end of the loop.
Running the above, you will see the following:
Notice that with every execution of the third expression, num
will increment by 1 until it boolean expression is no longer true.
for loop
for
loop in Ruby is a bit more complicated than while. You do not need to understand for loop and it is rarely used in Rails development.
If you are interested, here’s an example:
for i in 1..5
puts “I execute this statement #{i} times”
end
The first expression consists of the keyword for
, a local variable i
and the range 1..5
. A range is a sequence of numbers. In this case, the sequence will be 1, 2, 3, 4, 5
.
In Rails development, we rarely use while
or for
loops. You will learn what we use to execute loops in the second part of this guide.
The idea in explaining loops is for you to understand what loops is about.
Conclusion
This article introduces you to the basic of Ruby programming.
Of course, this is not everything.
We will cover methods, arrays and hashes as well as blocks in Part 2. Finally, we will talk about object-oriented programming in Part 3.