Ruby Programming Made Easy (Best Tutorial 2019)

Ruby Programming Tutorial

Ruby Programming Tutorial

Ruby is a Very flexible programming language that can be used to create games, to process text, and/or for web and app development. Ruby is a powerful, object-oriented programming language. A programmer can modify the Ruby language. This Tutorial explores the Ruby Programming Language Basics in easy methods. 

 

It makes it easy for a programmer to make the necessary changes and write the program without restrictions.

 

It also has a mark-and-sweep garbage collection that gives a programmer the ability to write the program without worrying about maintaining the reference counts in extension libraries. Ruby can also load extension libraries if your operating system permits it.

 

Ruby is considered a general purpose language. No one can deny its popularity. It is commonly used in Ruby on Rails applications. Companies like Kickstarter, Goodreads, Twitter, and Soundcloud chose Ruby to help them launch their products in the net.

 

Ruby on Rails is one of the world’s best programming frameworks. There are many companies that rely on Rails. It is basically a group of shortcuts that were coded in Ruby to help you build web applications or websites within a short amount of time.

 

If you are looking for a framework that is fast and reliable, then Rails can cater to your demand and you need to learn Ruby programming for that.

 

Ruby is efficient and fast, which makes it one of the most worthy languages today. In this modern time, where speed and efficiency must go hand in hand, Ruby can bring a lot of advantages and benefits to businesses worldwide.

 

Business owners know that the only way to stay alive in the competitive business arena is to give their clients efficient service without making them wait.

 

Ruby is easy to access and manipulate, which makes it user-friendly. Its simplicity offers a lot of comfort to the user. In fact, being simple is one of Ruby’s best features.

 

Ruby’s syntax is easy to understand and follow. If you have researched the early programming languages, then you must have noticed that the written codes sounded just like a machine.

 

The programmer must think like a machine in order to code a program that the computer would understand. Ruby and the majority of modern programming languages use natural English language. That being said, Ruby won’t put the programmer in a tricky situation.

 

Ruby is recognized all over the world and it has a large community that you can depend on. The community continues to grow and the best Ruby programmers are part of it.

 

As a novice programmer, you need all the help that you can get in order to develop or polish your Ruby programming skill. You can ask the community for assistance and some tips on how you can improve your ability. The Ruby community is friendly, especially with beginners.

 

There are available Ruby learning resources online that you can access in case you need additional info or would like to take a glimpse on the advanced courses. However, it is advisable to learn and get a good grip on the basics first.

 

Ruby can open a path for numerous job and/or extra income opportunities. If you are looking for a new career or would like to gain an extra source of income, then being a Ruby programmer is one of the options that you may want to consider.

 

Ruby continues to gain popularity and it is still highly in demand. Adding a skill in Ruby programming can add some spark to your resume and make potential employers or clients take interests on you.

 

Prerequisites in Learning Ruby Programming

The best way to avoid nuisance while learning Ruby is to get familiar with the usual computer terminologies that are being used today. If you are already familiar with them, then you can proceed without delay.

 

There is no prerequisite, but there is a post-requisite framework called Ruby on Rails. You need Rails to develop a mobile app, web applications, or enhance your business website. You can also use Ruby programming for the framework called Sinatra.

 

Between Ruby on Rails and Sinatra, most would prefer the former because it covers more of the common things that you want to do. Sinatra is small and light. It does not offer as much functionality and features of Ruby on Rails.

 

On the other hand, Ruby on Rails must be updated quite often and must be frequently maintained. Sinatra does not need a frequent update, although it still needs to get updated to function well. It is designed to be simple and slim.

 

There are people that prefer Sinatra over Rails because of its simplicity and low maintenance requirements. Ruby is no doubt one of the most popular programming languages in the world. One of the main advantages of Ruby is that many programming platforms support it and it is recognized worldwide.

 

The Start of Worldwide Recognition

In 1998, a simple Ruby homepage was created and the content was written in English. At that time, Ruby was still localized. Ruby-Talk, the first Ruby mailing list in the English language, was created. The purpose of its creation was to introduce Ruby to the rest of the world, and it was a complete success.

 

The first blog on the Ruby programming language was written in October 1999. The authors of the blog, The Object-Oriented Scripting Language Ruby, were Keiju Ishitsuka and Yukihiro Matsumoto. Soon, the Ruby programming language also spread to English-speaking countries.

 

In 2001, Ruby’s first English blog called “Programming Ruby” was published. Many people got a chance to learn the language and all thanks to the introduction of the blog.

 

In 2003, Ruby 1.8 was released. The creator of Ruby made a lot of changes in the 1.8 version including WEBrick, Duck Typing, Ruby-Run, Open-Uri, StringIO, and other minor additions.

 

RubyGems was introduced to the public in 2004. Its birth also marked the start of more good things to happen. Ruby took off in 2005 with the introduction of Ruby on Rails.

 

The new framework had somewhat affected the flow of web development for the better. Ruby had always been the favorite choice in writing CGI scripts, but Ruby on Rails has managed to take it to the next level.

 

The Model-View-Controller structure of Ruby on Rails gives full concentration on convention over configuration that web application developers truly appreciate. People got hooked and the Ruby community displayed an immense fondness to the Rails framework. The positive response made Ruby popular.

 

In 2007, Ruby 1.8.6 was introduced to the world. During the said year, Mac OS X allowed the installation of Ruby programming language.

 

In 2008, version 1.8.7 was released. At this point in time, Ruby can be considered at the peak of success.

 

The development version of Ruby 1.9 started in December 2007. It only got stabilized in the year 2011 with these notable changes: new hash syntax, more string formatting, improved file loading performance, new methods, new encoding support, enhanced speed, and many more.

 

In the early part of 2013, Ruby 2.0.0 was launched and offered stabilizing changes like never before. It introduced optimized garbage collection, safe monkey patching, built-in syntax documentation, keyword arguments, further speed improvements, and more.

 

On Christmas of 2013, Ruby 2.1.0 was introduced to the market. Although it only had minor changes, the introduction of semantic versioning made version 2.1.0 more valuable than most versions of Ruby language.

 

On February 24, 2014, Ruby’s 21st anniversary, the version 2.1.1 was introduced to the world. The new version focused on bug fixes and speed improvements. After 3 months, Ruby 2.1.2 was released. The latest version during that year was more stable than 2.1.1.

 

More stable versions of Ruby were released in the years that followed. Most of them only enhanced the features of the predecessor version of the Ruby language. It is possible that in the near future, a completely different version of Ruby language may appear.

 

Ruby Objects

The Ruby programming language regards the object as its heart. If you will go back to the previous statement regarding Ruby being an object-oriented language, you will see that Ruby treats all the data as an object.

 

It controls the data like an object. There are a lot of object-oriented languages, but very few can be considered as a true object-oriented language.

 

Ruby treats the data like object and places them in the center. Each object is different from each other because every one of them has their unique characteristics. Take a string as an example. It is an object with built-in characteristics, which give the string the ability to handle text.

 

Ruby Methods

A method defines the action that needed to be performed on the object. Most object-oriented programming languages have built-in object methods and definitions – Ruby has it too. To give you an idea about Ruby methods, take the method named capitalize as an example. It can be used for the Ruby class strings.

 

Take a look at this example:

1 samp1 = "you are great!"

The name “samp1” is the name of a variable. The “=” sign means the variable has an assigned value. The string “you are great!” is the value assigned to variable samp1.

 

If you want the assigned value’s first letter in uppercase, then you can add the method capitalize to convert the first character into a capital letter. This is how you add (or call) the method: samp1.capitalize

 

To see the result, you can write a simple code like this:

1 #Sample program 1

2 samp1 = "you are great!"

3 puts samp1.capitalize

 

The method capitalizes simply instructs the Ruby interpreter to turn the first character of the assigned value into a capital letter. The above code will give you this result:

You are great!

You should have noticed that when a method was called, it followed this pattern:

{{object name}}.{{method name}}

 

In the above sample, the object is a string (assigned to the variable samp1). If you use the method capitalize on a variable that does not contain a string value or the object is not a string, Ruby will pop an error message. You can also create any method for any of your objects. Here is the way to do that:

 


def method_name

#Enter your code here

end

The hash sign # informs the Ruby interpreter that the line is not executable and merely placed there to act as a comment or reminder for the human user or programmer. Every time the Ruby interpreter encounters a line with a hash sign, it automatically skips the line.

 

Using Code Editor

You need to use a code editor to write the code or program. A code editor uses plain text with no styling or formatting. You can use the text editor like Notepad, Emacs, TextMate, and others.

 

When using Ruby Interactive, you simply type in your codes directly on the screen. If you prefer using the online Ruby version, you can directly type in the codes or use a text editor and just transfer or paste your codes.

 

You can save your work when you use a text editor. You must choose a filename that can immediately give information about what the code or program needs to accomplish.

 

Take note that you must avoid using advanced text editors or word processor. They are intended for writing and not for coding. They often include whitespace or characters into the document that are invisible to the naked eye. Any unnecessary additions could lead to unexpected behavior of the program or even cause bugs.

 

Ruby Styles

The Ruby language follows a specific writing style that can create ease and convenience when writing and reading the Ruby codes. You need to get used to these things immediately for your code to look pleasing to the eyes.

 

Set your text editor's tab to 2 spaces. Indenting can help make the program more readable. It is also easy to maintain the system if the code is presented nicely.

 

Usually, in a company, a team that created the program may not be the team assigned to maintain it. Coding the program in a nice, easy-to-read way can help shorten the time to fix it when there’s a bug in the system.

 

A # sign that can be found at the start of a line means that everything after the hash sign within that same line is considered a comment. Comments also serve as notes or information that can help the programmers recall or know something about the program.

 

The entire system may have different sub-programs or modules. There are times when a programmer only needs to fix a certain module to repair the entire system.

 

When you initialize or define a file, method, or variable, it is recommended to always use snake_case formatting. The snake_case formatting uses lower case letters and separates each word with an underscore.


1 # Naming a file

2 sample_of_snake_case_file.rb

3

4 # Assigning a variable

5 seventy = 70

6

7 # Defining a method

8 def sample_method

9 # write your set of codes

10 end

 

When you want to assign a value to a variable with no intention of changing the assigned value, you need to define it as constant. In Ruby, you must write constants in uppercase.


1 # Constant declaration

2 ONE = "one"

3 SIX = 6

 

When using do/end blocks, you can use { } if the entire expression can fit within a single line. If you don’t have this symbol ( | ) in your keyboard, you can use this symbol ( ¦ ) – they are the same.


1 # Multi-line

2 [1, 2, 3].each do |i|

3 # do things

4 end

5

6 # Performs same thing in one line

7 [1, 2, 3].each { |i| # do things }

8

It is advisable to use CamelCase formatting when naming your classes. You are not allowed to use spaces in CamelCase. You need to keep in mind that you must capitalize the first letter of each word when naming your class.


1 # Class naming

2 class TheInitialClass

3 end

4

5 class TheOtherClass

6 end

For now, that’s all you need to know to get started. If you want to know more about the Ruby styles in the future, you can click this link.

 

Important Notes to Remember on Ruby Syntax

There are important notes to remember when writing a Ruby programming code, and you need to remember them. Some of these notes may seem vague for now, but they will come in handy later as you advance.

 

The Ruby code ignores the tabs and spaces (the whitespace), except when you use spaces in strings to make them readable. In Ruby programming, the newline characters and semicolons signify a statement ending. However, the presence of an operator, such as backslash or + , at the end of a statement indicates a continuation.

 

The names of the methods, constants, and variables are also known as the identifiers. Be careful when writing and using the identifiers for they are case sensitive. Most programmers encounter an error caused by the identifiers. Ruby treats the variable “num1” as something different from “Num1”.

 

When you assigned a value to num1 and tried to print Num1, you will get an error that says, “Uninitialized constant Num1.” You need to check your code and make sure that you have written the variables or identifiers in their proper cases.

 

DOCUMENTATION, CLASSES, METHODS, AND MORE

If you are keen on becoming a programmer, then you need to develop a reading habit and take time to go through the programming language’s documentation.

 

The Ruby language, like most well-liked programming languages, offers a wide array of standard libraries that are readily available at your disposal.

 

However, there is a need to spend ample time to familiarize yourself with all the different methods and classes that are already available to use. For now, it is best to just know some of them as you learn the Ruby language.

 

Understand that you will be able to learn Ruby in 24 hours, but you need more time to become an expert. After reading this entire blog, you should be able to do simple programming. Depending on your ability to grasp things, you may even do a short complex program later. You will be able to code something already after or even during each lesson.

 

Some developers prefer the term API (application programming interface) to refer to the programming language documentation. Below is a String class screenshot was taken from Documenting the Ruby Language. Pay close attention to the encircled areas.

 

Module Name and Class Name

Looking at the image above, the class name is String. In some documentation you will notice a:: symbol to refer to a class name, just like in this one: Encoding:: Converter.

 

The symbol:: actually defines a namespace and create a distinction between Ruby classes. The symbol also serves as a way to separate classes from the others that happen to have the same name.

 

For example, you have ActiveRecord:: Base and CurrentRecord:: Base. Both have a class named Base, but the only thing similar to both of them is their name. One is Base class in the module ActiveRecord and the other is a Base class in the module CurrentRecord.

 

When you open a particular class, you are provided with all the information regarding that class as well as the things that you are allowed to do. Look at the same figure above once more and take note that the sidebar with the symbol:: has a different meaning – the name after the said symbol refers to the class method.

 

Methods

The methods that use # are instance methods (see figure above) and the methods that use:: are class methods. These symbols bear such meanings only for Ruby documentation. Remember that in actual Ruby code, the hash sign is used to indicate comment and the double colon sign is used to indicate namespace.

 

Using the same example, the String class, let us try to apply the class method String.new and String.try_convert. Take a look below:


IRB :001 > p = String.new("pink")

=> "pink"

IRB :002 > String.try_convert("blue")

=> "blue"

Now let us try instance methods. If you visit the Ruby documentation for String class and scroll down, you will see split method. Look at the sample below:

IRB :001 > "the world is a stage".split

=> ["the", "world", "is", "a", "stage"]

 

Did you notice how the method was called out? When using the class method, you state the name of the class first followed by the method and you need to enclose the object in parenthesis. When using the instance method, you state the object followed by the method.

 

START WITH THE BASICS

A collection of characters in a sequence is usually called a string. A string can have double quotes (“ ”) or single quotes (‘ ’), and you can use either format. But, you need to observe some basic rules in using them.

 

You have two options to choose from when you need to use quotes within the string. You can use the method that uses double-quotes or the method that uses single-quotes with escaping. Take a look at this:


1 # Sample1: Double quotes

2 "Elena said, 'You first.'"

3

4 # Sample2: Single quotes and escaping

5 'Elena said, \'You first.\' '

The escape character or backslash (\)informs that the quotes after it are just plain quote characters and should not be regarded as part of Ruby programming syntax.

 

You can use the double quotes for string interpolation. Look at the sample below:


IRB :001 > num1 = 'seven'

=> "seven"

IRB :002 > "I choose number #{num1}!"

=> "I choose number seven!"

 

You can try it on your IRB to see the actual result.

When you need to work with strings, you can use string interpolation to merge your Ruby code. Keep in mind that you can only use double quotes for string interpolation to work. As time goes by, you will get familiar with this technique as you continue to further develop your Ruby programming skill.

 

Symbols

Basically, you use a symbol to serve as a reference, especially if you don’t want to print it on screen or manipulate it in any way. The Ruby symbols are commonly created via putting a colon before a word.

 

Numbers

There are numerous ways that you can present numbers in Ruby. An integer is a form of a number that is considered the most basic. It is always the whole number without a decimal point. There is also something called float, which is a complex form and has a decimal point.

 

The examples of integers are 1, 3, 25, 100, 1058894, and so on. The examples of floats are 3.14, 1.83, 23.25974, and so on.

 

Nil

All programming languages must have means to present “nothing”, and in Ruby language, it is presented by nil. Something that has a nil value is totally empty or without any particular type. The best example to demonstrate this is a situation where there is an expected output but nothing is returned. Take a look at this:

IRB: 001 > puts "Hello, Ruby World!"

Hello, Ruby World!

=> nil

You can use the method puts to print out the string on your computer screen. As you can see from the above example, it returns nothing (this symbol => signifies return). You can see that it returned nil.

 

Is it possible to use .nil to know whether a particular entity nil? Take a look at the sample below:

IRB: 001 > "Hello, Ruby World".nil?

=> false

The air returned “false” when .nil was added after the string.


IRB :001 > if nil

IRB :002 > puts "Hello, Ruby World!"

IRB :003 > end

=> nil

It did not print “Hello, Ruby World!” on the screen because it treated the statement or expression as a false condition. It did not read the next line because the condition is already false. But, if you will do this instead:


IRB :001 > if 1

IRB :002 > puts "Hello, Ruby World!"

IRB :003 > end

Hello, Ruby World!

=> nil

It gets printed because the condition does not contain a false value. The value 1 is something and not “nothing”. The next line was executed due to the fact that the if statement has provided a value true.

You will learn more about the if or conditional statements later.

 

RUBY OPERATIONS

Integers: Addition, Subtraction, Multiplication, and Exponentiation

In Ruby, it is fairly easy to do basic mathematical operations. You only need the operator + to add the integers together. Like this one:


IRB :001 > 2 + 1

=> 3

IRB :002 > 2 + 1 + 3 + 4

=> 10

Go and play more with integers on your IRB. It is advisable to practice what you have learned to get familiar with the new Ruby function, command, or lesson.

When performing subtraction, use the - operator.


IRB :001 > 2 - 1

=> 1

IRB :002 > 11 - 1 - 3

=> 7

When performing multiplication, use the * operator.

IRB :001 > 4 * 4 * 4

=> 64

IRB :002 > 11 * 2

=> 22

When performing exponentiation, use the ** operator.


IRB :001 > 6 ** 2

=> 36

IRB :002 > 6 ** 3

=> 216

In line 1, the number 6 must be raised to two or should be squared. In line 2, the number 6 must be raised to three.

Division and Modulo

When performing division, use/.

IRB :001 > 8 / 2

=> 4

 

There is the modular remainder. It uses the % symbol. The answer that it gives is the remainder that it gathered from the division. There may come a time when you need to use the exact remainder for your program to work and modulo can help a lot.

IRB :001 > 25 % 4

=> 1

 

Multiplying and Dividing Floats

You can multiply floats and get an exact answer each and every time. Ruby will always return a float whenever you give a set of numbers to solve even if only one of them is in decimal form.


IRB :001 > 3.75896 * 4

=> 15.03584

If you want to get the exact answer to a division problem that requires decimal point and no remainder, you need to use floats.

IRB :001 > 11.0 / 4

=> 2.75

Keep this table of Ruby operators handy:

 

RUBY OPERATORS

Sign Operand Example


+ Addition 5 + 2

- Subtraction 10 - 3

* Multiplication 7 * 1

/ Division 21 / 3

% Modulo 215 % 8

** Exponentiation 2 ** 5

 

Equality

There will be instances where you need to check whether the two objects have the same values. You can use the == operator to check the equality of two objects. The == operator compares the two objects on its left and right side.

 

The result of such a comparison will return either true or false. Most programming languages refer to both values as boolean.

 

You can try these examples on your IRB and see the actual results with your own eyes.


IRB :001 > 5 == 5

=> true

IRB :002 > 0 == 5

=> false

You can also use the == operator on strings.

IRB :001 > 'ruby' == 'ruby'

=> true

IRB :002 > 'ruby' == "ruby"

=> true

IRB :003 > 'ruby' == 'language'

=> false

What do you think will happen when you type the expressions below on your

IRB?

-

-

'7' == 7

'7' == 'seven'

The two sets of comparisons will both return false. In the first comparison, ‘7’ has a different value from 7. The presence of quotes made the other 7 assume the value of a string, making them different from one another.

 

The next comparison, although being both strings, are still different from each other from the computer’s point of view. Keep in mind that the computer only recognizes binary codes and ‘7’ has a different binary code from ‘seven’.

 

Concatenation

The concatenation in the string is similar to the addition of numbers. You add strings instead of numbers. You need the operator + to combine or join the strings.


IRB :001 > 'ruby' + 'ruby'

=> "rubyruby"

IRB :002 > 'ruby' + "ruby"

=> "rubyruby"

IRB :003 > 'ruby' + 'language'

=> "rubylanguage"

IRB :004 > 'ruby' + ' ' + 'language'

=> "ruby language"

If you look at line 4, you will notice that the addition of (‘ ’) has created a gap between the two words as compared with the result in line 3. Try to experiment and fool around more with your new discovery. It can help you get to know it better.

 

What do you think will happen if you have type '1' + '1' on your IRB? If you think you will get 2, it makes sense but remembers that you are dealing with strings (due to the presence of quotes). The correct answer would be “11”.

 

What if you try to concatenate or join a string and an integer? Expect to get an error message.

 

TYPE CONVERSION AND OTHERS

Someday, you may encounter a situation wherein you must really combine Fixnum and String.

 

For example, a user input ‘15’ and the program needs to increment the number by 3. Ruby won’t allow you to perform a mathematical operation between a string and a number. Even if you try, you will only see an error message.

 

Fortunately, there’s a method that you can use to convert the String into Fixnum– it is called to_i method. It can be called in this manner:


{string}.to_i

IRB :001 > '15'.to_i

=> 15

IRB :002 > '15'.to_i + 3

=> 18

You can clearly see that the method to_i returned a Fixnum. Line 2 shows you that you can increment the value by 3 since it’s been converted. You can perform other mathematical operations aside from addition. You can try it on your IRB and explore other possibilities.

 

The other commonly used conversion operators are to_f, which converts an integer into a float, and to_s, which convert a number into a string. You can practice the different conversion operators and familiarize yourself. They are more useful than you think.

 

Arrays

If you need to organize an orderly list, then it is best to use an array. You can have floats, integers, strings, booleans, or another type of data in your list. It is easy to recognize an array in Ruby because it uses square brackets ([ ]). You need to make a list inside the brackets. Each element on the list is separated by a comma.

 

Here is an array of integers from 1 to 5:


IRB :001 > [1, 2, 3, 4, 5]

=> [1, 2, 3, 4, 5]

You can access each array element through the index. The index count always starts at zero. This is how an array with index should look like (the array is named “Sandwich”):


Sandwich

Tuna [ 0 ]

Ham & [ 1 ]

Cheese

BLT [ 2 ]

Pepperoni [ 3 ]

Cheese [ 4 ]

Steak

Hamburger [ 5 ]

If you want to access the second element in the array, then you need to call index 1.

Try to do this simple exercise on your own:

  • 1. The name of your array is number.
  • 2. It should contain the numbers 1 to 7.
  • 3. Call the third element in the list.

 

Expect more exercises and program samples later. It is best to learn through examples and hone your skill via programming exercises. Know that there are different ways to tackle the problem and there could be more than one solution. Going back to the simple programming exercise, you should have arrived at this answer:


IRB :001 > number = [1,2,3,4,5,6,7]

=> [1,2,3,4,5,6,7]

IRB :002 > number [2]

=> 3

There is another solution:

IRB :001 > number = [1,2,3,4,5,6,7] [2]

=> 3

Keep in mind that the index always starts at 0.

 

Hashes

A hash comes with a set of key-value pairs and oftentimes it is also called a dictionary. It uses curly braces ({ }). In a key-value pair, a specific value is assigned to a key. The key is commonly represented by a symbol => that clearly points to the value.


IRB :001 > {:monkey => 'eats banana'}

=> {:monkey => 'eats banana'}

 

The sample hash above is one key-value pair. Like arrays, hashes can have multiple items separated by commas. You don’t need to worry about having them in a specific order.


IRB :001 > {:one=>'I',:two=>'II',:three=>'III'}

=> {:one=>'I',:two=>'II',:three=>'III'}

What if you want to find out the Roman numeral of two? You can retrieve the information that you want by its key.

IRB :001 > {:one=>'I',:two=>'II',:three=>'III'}[:two]

=> "II"

You can also write the above samples this way:

IRB :001 > num= {:one=>'I',:two=>'II',:three=>'III'}

=> {:one=>'I',:two=>'II',:three=>'III'}

IRB :002 > num [:two]

=> "II"

IRB :003> num [:three]

=> "III"

When you write the code like in the sample above, you don’t need to write the hash over and over again. All you need to do is write the hash name and the key. It is also easier to access the other keys as evident in line 3.

 

Puts and Return

Before we discuss all puts and return, are you curious about the “=>” sign that you see in your Interactive Ruby or IRB? The sign is called the hash rocket, which is usually followed by an expression that Ruby returns. Each time you type something in your IRB, you are generating an expression.

 

Anything that can be evaluated is called expression. That being said, most of the things that you write in Ruby can be evaluated and considered expressions. In Ruby programming, an expression always returns something – even nil or an error message.

 

It is usual for new programmers, who don’t have prior programming knowledge, of Ruby language to get confused with puts and return. The confusion arises from the misunderstanding caused by insufficient or misleading information.

 

When you call puts the method in Ruby, you are giving an instruction to print something on the computer screen. Keep in mind that the expression does something and needs to return something. However, the returned value may not always be the performed action.


IRB :001 > puts 'anything'

anything

=> nil

As you can see, the word ‘anything’ gets printed on the screen and returned nil.

 

RUBY VARIABLES

A variable serves as a container in which you store the data that you need for your program. It is important to give each variable in your program code a unique and relevant name. It is also important that the variable name is easy to recall. The content of your variable may change depending on the program flow.

 

For example, you want a program that can add two numbers that can assume different values each time the program runs. You need to prepare a container for each number and also set up the mathematical function that must be applied between the containers.

 

This way, the user doesn’t need to edit the source code just to get the sum of the new set of numbers. It is also more convenient and efficient if the source program can automatically compute for the sum of the new set of numbers.

 


Do it like this:

total = first_number + second_number

The above representation is still better than doing it like this:

total = 1 + 2

 

In the second presentation, you need to change the value of the constants 1 and 2 into a new set of values each time you run the program to satisfy the requirements of the user. You actually need to alter the source code to achieve such a feat, which is also too troublesome and inefficient.

 

You can use the variables or the data they contain throughout your program.

Reserved Words that Should not be Used as Variable Names. Below is the list of Ruby reserved words. You should not use these reserved words as variable or constant names when coding your program. Each word in the list has a specific function to perform.


while Retry for break

and ensure or unless

do BEGIN next then

nil end redo FALSE

undef until rescue when

def not elsif alias

class in return TRUE

case self if __FILE__

defined? module super __LINE__

END else

If you encounter a syntax error, then it is possible that you inadvertently used a reserved word as your variable name.

 

Assigning Value to a Variable

Giving a variable its name is a grueling task for a programmer. When you give a variable its name, you need to come up with something unique and not a reserved word in Ruby. The name should be unique and should provide a short description regarding where it should be used or the reason for its existence.

 

You can assign a number or string to your variable. You use the equal sign (=) to assign the value. Don’t mix up the signs ‘==’ (which compares equality) and ‘=’. Remember that when you assign a value, the variable name is placed at the left side of the equal sign and the value is placed at the right side. Take a look at this one:


IRB :001 > surname = 'Jackson'

=> "Jackson"

IRB :002 > age = 17

=> 17

 

In the given sample, the variable surname has an assigned string value 'Jackson'. In line 2, the variable age has an assigned integer value 17. Each time you call or use a particular variable in your program, it will give you the value that it contains.

 

If the value remains constant throughout the program, then your program will use the same value. Just to give you a heads up, there are cases where the value of your variable may change and you will know more about it later.

 

Looking at the given sample, your program will retrieve the value ‘Jackson’ each time you use the variable surname in your program. It will likewise retrieve the value 17 each time you use the variable age.

Try this simple exercise:


1. Assign 3 to variable a.

2. Assign 4 to variable b.

3. Assign 7 to variable c.

4. Get the sum of a, b, and c.

You should be able to come up with this answer:

IRB :001 > a = 3

=> 3

IRB :002 > b = 4

=> 4

IRB :003 > c = 7

=> 7

IRB :004 > a + b + c

=> 14

What if you are asked to assign the sum of a + b + c to variable d, instead of just getting the total? Your answer should look like this:

IRB :001 > a = 3

=> 3

IRB :002 > b = 4

=> 4

IRB :003 > c = 7

=> 7

IRB :004 > d = a + b + c

=> 14

You can also re-assign the value of variables. Take a look at this:

IRB :001 > a = 3

=> 3

IRB :002 > c = 2

=> 2

IRB :003 > c = a

=> ???

Can you guess the returned value for variable c? Even though it has an initial value of 2, it was replaced by the value that variable a contains. It will return to 3.  You can practice more before you try the simple exercises below. Remember to try to do things on your own first before looking at the answer. You are trying to learn, so don’t cheat!

 

Simple Exercises

You already know the different mathematical operators in Ruby, we will use them on the variables. You will see the answers at the end of the last task.

First task:


1. Assign 5 to variable num1.

2. Assign 3.55 to variable num2.

3. Assign ‘Lucky’ to variable word1.

4. Assign ‘Sure’ to variable word2.

5. Print num2.

6. Print word1.

Second task:

1. Assign 20 to variable a.

2. Assign 10 to variable b.

3. Assign 30 to variable c.

4. Get the sum of the three variables. Third task:

1. Assign 20 to n1.

2. Assign 15 to n2.

3. Get the difference of n1 and n2, and assign it to variable dif. Fourth task:

1. Assign 4 to m1.

2. Assign 7 to m2.

3. Print the product of m1 and m2.

Answer to the first task:

IRB :001 > num1 = 5

=> 5

IRB :002 > num2 = 3.55

=> 3.55

IRB :003 > word1 = 'Lucky'

=> "Lucky"

IRB :004 > word2 = 'Sure'

=> "Sure"

IRB :005 > puts num2

3.55

=> nil

IRB :006 > puts word1

Lucky

=> nil

Answer to the second task:

IRB :001 > a = 20

=> 20

IRB :002 > b = 10

=> 10

IRB :003 > c = 30

=> 30

IRB :004 > a + b + c

=> 60

Answer to the third task:

IRB :001 > n1 = 20

=> 20

IRB :002 > n2 = 15

=> 15

IRB :003 > dif = n1 - n2

=> 5

Answer to the fourth task:

IRB :001 > m1 = 4

=> 4

IRB :002 > m2 = 7

=> 7

IRB :003 > puts m1 * m2

28

=> nil

Consider this one as a special task. Try to do this on your own:


1. Assign 1 to d1.

2. Assign 2 to d2.

3. Assign 3 to d3.

4. Assign 4 to d4.

5. Assign 5 to d5.

6. Assign 20 to d6.

7. Get the quotient of d6 and d4.

8. Get the remainder of d6 and d3.

9. Assign d2 to d3.

10. Print d3.

11. Raise d5 to 2.

12. Print the sum of d2, d6, and d5.

 

USER INPUT AND VARIABLE SCOPE

In the real world, users are usually the ones who must input the needed data. Up until now, you are the only one who assigns the values or data that you need to include in your program. There is a thing called user input, wherein the user can personally type in the data that the program needs to satisfy a certain process or set of codes.

 

You can allow the user to type in their information by using the gets method. When you use gets, the program waits for the user to input the information that the program asks and to press the enter key afterward. It’s like this:

 

Let’s say the user typed in Maria. The IRB will display this result:

 

Take a closer look at the image above. As you can see, Ruby returned the name that the user typed in and there’s a ‘\n’ next to that name. The ‘\n’ is known as the newline character. If you don’t want to see it as part of the typed user info, you can use chomp to chop it off. You can also use chomp after the string to eliminate the carriage return character that appears at the end.

 

Why do you need to use chomp? You need it to make the entry aesthetically appealing. Take a look at the two samples below:


IRB :001 > name = gets

Maria

=> "Maria\n"

IRB :002 > name + ' is pretty'

=> "Maria\n is pretty"

IRB :001 > name = gets.chomp

Maria

=> "Maria"

IRB :002 > name + ' is pretty'

=> "Maria is pretty"

Which one of the two is more appealing? It is definitely the second sample.

 

Default Parameters

When defining your method, you may want to structure the method that you will use to make sure that it will always work. We will use the same yo method as an example, but we will restructure it to give a clear view of what a default parameter does.


# yo.rb refactored once more

def yo(texts='hello')

puts texts + '.'

end

yo()

yo("hi")

yo("it’s good to see you")

yo("hope you are happy ")

yo("I'm glad you’re fine ")

When you run the code, you will see that yo() prints ‘hello.’on the screen. It’s because the program has provided a default parameter. Remove yo() and Ruby will not print ‘hello.’ on the screen.

 

Optional Parentheses

You can remove the parentheses if you want. You can write the sample code above like this:


# yo.rb refactored once more

def yo(texts='hello')

puts texts + '.'

end

yo

yo "hi"

yo "it’s good to see you"

yo "hope you are happy"

yo "I'm glad you’re fine"

Compare the two styles, which one do you prefer? Reading Ruby codes can be quite tricky. It is advisable to use parenthesis to create some distinctions, although it is up to you to go with the style that you find more comfortable to write.

 

Methods as Arguments

You are already familiar with methods and how they are called. Take a look at these simple samples to explore it further. Let us use subtract and add as method names and call them.


def subtract(num1, num2)

num1 – num2

end

def add(num3, num4)

num3 + num4

end

We will assume that the variables are integers. Keep in mind that Ruby implicitly returns the last expression in the method. In this case, we don’t need to worry about the type of values that Ruby will return since each method only has one line.

We will use 100 and 60 for both methods:


subtract(100, 60) # returns 40

=> 40

add(100, 60) # returns 160

=> 160

Now, we will create another method that we will name multiply. We will

pass subtract(100, 60) and add(100, 60) as arguments to multiply method.

def multiply(num5, num6)

num5 * num6

end

multiply(add(100,60), subtract(100, 60))

The last expression will return 6,400. You can also type complex expression like this one:

add(subtract(100, 60), multiply(subtract(10, 5), add(25, 5)))

=> 190

Let us dissect each part to see if the answer is right.

190 = (100-60) + ((10-5) * (25+5))

190 = (40) + ((5) *(30))

190 = 40 + 150

190 = 190

Remember that the open parenthesis, in the beginning, must always have a corresponding close parenthesis. It is advisable to use parenthesis to group things together and see the ones that need to be processed first. You can also prevent confusion when you use parenthesis and make your code readable and pleasing to the eye.

 

Try the sample codes on your own and practice more if you want.

Now we get to the meaty part of Ruby programming. You must have noticed that there are a lot of samples in this blog.

 

It is easy to learn any programming language if you can see different program samples. It is also easier to explain things if there are program samples that serve as a guide than just telling how a certain program works or what it does.

 

You can try the codes for practice and then do them without relying on your notes to see how much you have learned. It is understandable that you won’t be able to memorize everything in the Ruby documentation and it is advisable to take it a step at a time. You will definitely learn how to create a Ruby program in one day, but you need ample time to be an expert Ruby programmer.

 

The programmers that you know took a year or more to really master the syntax and flow of a certain programming language. They may only need a few hours to learn a new language, but the mastery will take a lot of time. In fact, you could be better than most of them when they started.

 

Before we get to conditionals, let us take a detour to the different comparison operators.

 

Comparison Operators

The comparison operators can help check whether each presented condition is true or false. The comparison operators are different from mathematical operators.

 

The comparison operators do not give an exact solution to a mathematical problem. They exist for the purpose of verifying the truthfulness or falsehood of a certain expression. Either true or false, the data will need to fulfill a particular instruction.

 

Here is the comparison, equality, and logical operators table:

Comparison, Equality, and Logical Operators


Sign Meaning Example

== equal to 6 +1==7

!= not equal to 4!=5+1

< less than 20<23

<= less than or 7<=5+a

equal to

> greater than 30>18

>= greater than or 5>=5-a

equal to

&& and num ==4 &&

num.even?

|| or num == 3 ||

num == 6

! not !(7 ==7)

=>False

Remember that ‘==’ is different from ‘=’, as explained in the previous blog. Conditionals

When you write a program, it is only natural that you want the data to arrive at the right decision. You want the data to do what is right on the given circumstances. In the world of programming, it is known as conditional flow. How can you make the data choose the right thing to do? You will need some help from conditionals.

 

A conditional can be considered a fork or several forks in your path. The conditionals can lead the data to the right path depending on the presented or defined parameters. The conditionals are formed using comparison operators and if statements.

 

We will use the file named condition.rb for this program:


IRB :001 > # condition.rb

IRB :002 > puts "Enter a number"

Enter a number

=> nil

IRB :003 > num = gets.chomp.to_i

3

=> 3

IRB :004 > if num == 1

IRB :005 > puts "Num is 1"

IRB :006 > elsif num == 2

IRB :007 > puts "Num is 2"

IRB :008 > elsif num == 3

IRB :009 > puts "Num is 3"

IRB :010 > else

IRB :011 > puts "Num is not recognized"

IRB :012 > end

Num is 3

=> nil

To get an input number from a user, it is necessary to use gets. We add .chomp to get rid of the cartridge return character. We also use .to_i to convert the string into an integer. The if statement uses the reserved words if, elsif, else, and end.

 

Run the given code three times more and make sure to follow these instructions:

1. Run the code for the second time and enter number 1. Press enter.

2. Run the code for the third time and press number 2. Hit enter.

3. Run the code for the fourth time, type in any number greater than 3. You can repeat the third instruction again and again to review the effect.

 

The code is actually checking the entered number against the options that the program has provided. It checks whether the number is equal to any of the available options. If the number is not equal to any of the number in the provided options, the program will print that the number is not recognized.

 

It is safe to say that this program has effectively controlled the flow via setting conditionals.

See more samples below to familiarize yourself with the if statements:


# Sample 1

if number == 7

puts "Number is seven."

end

# Sample 2 if x == 5

puts "x is five" elsif x == 4 puts "x is four" end

# Sample 3

z = gets.chomp.to_i

If z.between?(1,5)

puts "Number is between 1 and 5”

else

puts "Number is more than 5"

end

# Sample 4 if y == 7 puts "y is 7" else

puts "y is not 7" end

 

# Sample 5: you need to add "then" when using a one-liner if w == 6 then puts "w is six" end Ruby is indeed an expressive language. It allows the programmer to append the if statement at the end. Take Sample 1 for instance. The code could also be written like this:

 

puts "Number is seven" if number == 7

You can also use unless, which is a Ruby reserved word. It is quite tricky to use if you are used to using the if statement – unless is the exact opposite of if statement. You can use it this way:

 

puts "Number is NOT 7" unless x == 7

Try to do this on your own:

  • 1. Use the variable num and get the input from the user.
  • 2. If the user input is between 1 and 10, print "The digit is between 1 & 10".
  • 3. If the user input is between 11 and 20, print "The digit is between 11 & 20".
  • 4. If the user input is more than 20, print "The digit is more than 20".

 

You must try not to look at the answer as you write your code. This coding problem is a good programming exercise.


IRB :001 > num = gets.chomp.to_i

8

=> 8

IRB :002 > if num.between?(1, 10)

IRB :003 > puts "The digit is between 1 & 10"

IRB :004 > elsif number.between?(11, 20)

IRB :005 > puts "The digit is between 11 & 20"

IRB :006 > else

IRB :007 > puts "The digit is more than 20"

IRB :008 > end

The digit is between 1 & 10

=> nil

 

Comparisons and Boolean Value

This section will give you more information regarding the comparison operators and help you manage complex conditional statements. You need to remember that the only thing that comparison operators return is a boolean value. The boolean value is either true or false– it does not give any other response.

 

Let us discuss 6 of the comparison operators and the meaning of each. The remaining comparison operators will be discussed in the next sub-blog.

1. The less than symbol (<) – the value on the left of the symbol must be lower than that on the right side.


Example:

IRB :001 > 76 < 80

=> true

IRB :002 > 80 < 76

=> false

2. The greater than symbol (>) – the value on the left of the symbol must be higher than that on the right side.


Example:

IRB :001 > 100 > 80

=> true

IRB :002 > 100 > 200

=> false

3. The less than or equal to symbol (<=) – the value on the left of the symbol must be lower than or equal to the value on the right side of this particular comparison operator.


Example:

IRB :001 > 4 <= 5

=> true

IRB :002 > 6 <= 5

=> false

 

4. The greater than or equal to symbol (>=) – the value on the left of the symbol must be higher than or equal to the value on the right side of this comparison operator.


Example:

IRB :001 > 5 >= 7

=> false

IRB :004 > 7 >= 7

=> true

IRB :005 > 7 >= 6

=> true

5. The equal to operator (==) – the value on both sides of the operator must be equal. Since we’ve been using this for a while now, you must be familiar with it already.


Example:

IRB :001 > 7 == 7

=> true

IRB :002 > 7 == 3 + 4

=> true

IRB :003 > '7' == 7

=> false

The last line in the sample is a sort of reminder that you need to compare two of the same data type. At first glance, '7' and 7 are indeed the same, but they have different data types. One is string while the other one is an integer – they are still different from one another.

 

6. The not equal to operator (!=) – the value on both sides of the operator must not be equal – the complete opposite of equal to operator.


Example:

IRB :001 > 7 != 8

=> true

IRB :002 > 7 != 7

=> false

IRB :003 > 34 != 43

=> true

Try to determine the boolean value of each expression:

1. (40 - 20) > 25

2. (10 + 17) == 2**10

3. 1**10 <= 2

4. 20 * 4 >= -20

5. 81 != 9**2

6. (30 - 10) < 35

7. (20 + 7) == 2**4

8. 14 <= 7 + 7

9. 20 * 4 >= 40

10. 100 != 10**2

 

COMBINING EXPRESSIONS

Before we start combining expressions, take a look at the table below:

This table can guide you in finding the correct final answer for the presented expressions. You will use it as a reference when combining expressions. The logical operators compare the expressions on both sides of a particular operator and give result in boolean values.

 

There are three logical operators that you need to remember: and ( && ), or (||), and not ( ! ). Keep the table handy all the time.

 

Combining Expressions

By now, the conditional flow should be clear to you. If it’s still a bit vague, it is best to go over the lesson one more time. You can also combine multiple conditional expressions to create a scenario that is more specific. You can use && and || operators.

 

1. The "and" operator ( && ) – the expressions to the left and to the right of the operator should be both true to get a true boolean response or result.

 

The logical operator && checks if the expressions on either side of the operator are true and true, true and false, or false and false. The final answer depends on the condition of the statements or expressions.


Example:

IRB :001 > (7 == 7) && (4 == 4)

=> true

IRB :002 > (7 == 5) && (3 == 3)

=> false

IRB :002 > (8 == 7) && (9 == 10)

=> false

 

2. The "or" operator (||) – the expressions to the left or to the right of the operator should be true to get a true boolean response or result. That is, at least one expression is true for the entire statement to be true.

 

The logical operator || checks if the expressions on either side of the operator are true or true, true or false, or false or false.


Example:

IRB :001 > (8 == 8) || (11 == 11)

=> true

IRB :002 > (3 == 12) || (100 == 100)

=> true

IRB :002 > (9 == 5) || (15 == 25)

=> false

3. The "not" operator ( ! ) – the operator inverts the boolean value of a particular expression. When a particular expression is true, adding! the operator will make it false. When a particular expression is false, adding ! the operator will make it true.

 

Example:


IRB :001 > !(4 == 4)

=> false

IRB :002 > !(5 == 6)

=> true

When you are combining expressions, it is best to use parenthesis to group the expressions. This makes it more readable. It also helps the computer to accurately understand your objective. It will evaluate the parenthesis in the usual algebraic order.

 

Ruby follows the so-called order of precedence when evaluating the multiple expressions. Here is the order:


1. Comparison: <=, <, >, >=

2. Equality: ==, !=

3. Logical ‘and’: &&

4. Logical ‘or’: ||

Take a look at this:

if a && b || d

# do something end

In the sample above, the first one to be executed is a &&b. If the expression is true, then Ruby will execute the # do something next. If a &&b returns false, then d will get a chance to get evaluated. If d returns true, the next line gets evaluated. If d also returns false, then the program will leave the if statement.

 

Ternary Operator

The ternary operator is a common idiom in Ruby language that creates fast if/else statement because it has the capability to write it all in a single line.

 

The ternary operator uses these symbols:? and: Examples:


IRB :001 > true ? "this is okay" : "this is bad"

=> "this is okay"

IRB :001 > false ? "this is it" : "this is not it"

=> "this is not it"

How does it work? Does the computer first evaluate the expression on the left of?. If the said expression is true, the computer executes the code on the immediate right of the? If the expression on the left of the ? is false, then the computer executes the code on the right of the:

 

The ternary operators will definitely come in handy, especially when you have become more familiar with if statements. You can always practice your coding skills on your IRB if you are unsure of how a certain command works. Practice makes perfect and you already have all the tools that can help you develop your skill.

 

CASE STATEMENT

A case statement bears similarities with an if statement, only with an interface that is slightly different. You will use the reserved words case, when, else, and end when working with case statements.

 

When creating a case, the first thing you need to do is define a case and then evaluate its value as well as the process to complete if a particular case is true. To give a clearer presentation, let us create a file called case_sample.rb to see how case statements work.


# case_sample.rb sample = 3

case sample

when 3

puts "The answer is 3"

when 2

puts "The answer is 2"

when 1

puts "The answer is 1"

else

puts "There’s no answer"

end

The code above is sort of a modified if statement. You can also do it this way:

# case_sample.rb (other version) sample = 3

ans = case sample

when 3

"The answer is 3"

when 2

"The answer is 2"

when 1

"The answer is 1"

else

"There’s no answer"

end

puts ans

If you want to get an input from the user, then you can write the code like this:

# case_sample.rb (another version) sample = gets.chomp.to_i

case sample

when 3

puts "The answer is 3"

when 2

puts "The answer is 2"

when 1

puts "The answer is 1"

else

puts "There’s no answer"

end

Your code appears more structured and readable when you use a case statement. It is also easy to modify and debug.

 

You also need to remember to always be careful when writing or reading the Ruby codes. Know if the returned value is a string or integer and see how you can convert them if your statements or expressions are asking for the same types of data. Review the different signs or symbols as well as the operators that Ruby uses.

 

Exercises

It’s time to practice what you have learned. Can you tell the boolean value of the expressions below? If you have doubts, you can type the expressions on your IRB to verify your answer.

Task 1:


1. (30 * 5) >= 150

2. !(4>5) == (5==4+1)

3. 76 < 80

4. (44*2) > 100

5. 100**2 < 10**10

Task 2

Write a program for a method named try that contains a string argument. You need to code the string in lower cases, but it should print it in all caps. It should print it on screen. You can refer to the Ruby documentation to help you.

 

Task 3

Write a program that asks the user to input a number between 1 and 20. If the input number is between 1 and 5, print “The number is small”. If the input number is between 6 and 15, print “The number is okay”. If the input number is between 16 and 20, print “The number is awesome”.

 

You need to use a case statement. If you think task 3 is a bit difficult to do, then don’t touch it – for now. You still need to practice your case statement a bit more to get the hang of it.

 

ITERATORS AND LOOPS

There are times when a certain program works best with a loop. What is a loop? There is a loop when a piece of code is being executed repeatedly within a specified number of repetitions or until a particular condition has been satisfied.

 

You can write a code that instructs Ruby to repeat a particular segment or module in your program instead of writing the same code over and over again.

 

This blog will cover the different Ruby loops and they are a loop, for loops, while loops, and do/while loops.

 

To give you an idea about loops, here is a simple calculator program written in plain English.


#Calculator program for two numbers using while loop

while the user needs the program, do this:

display on screen: Choice 1 - add

display on screen: Choice 2 - subtract

display on screen: Choice 3 - multiply

display on screen: Choice 4 - divide

display on screen: Choice 5 – end

#ask the user for the math operation to try

if choice is 1:

get the first number

get the second number

add the numbers

display the result on screen

if choice is 2:

get the first number

get the second number

subtract the 2nd number to the 1st number

display the result on screen

if choice is 3:

get the first number

get the second number

multiply the numbers

display the result on screen

if choice is 4:

get the first number

get the second number

perform division

display the result on screen

if choice is 5:

end the loop

Display a thank you message onscreen

END PROGRAM

 

As long as the user needs to use the program, it continues to present the user with different choices such as add, subtract, multiply, divide, or end the program. Each choice has a separate module.

 

The computer will continue to execute the code within the module as long as the user chooses that particular number or mathematical operation. The loop goes on until the user has decided to terminate the program by choosing 5.

 

The loop can go on for as long as you want and it can also end abruptly – it all depends on the objective or requirements of the program.

 

A Simple Loop

There is a keyword called loop in Ruby that takes a block denoted by doing… end or {

… } . It is the easiest way to generate a loop in Ruby. A loop will run the code non-stop within the specified block until you have decided to stop it by simultaneously pressing Ctrl and c on your keyboard or if you have included a break statement in your code.

 

Try to run this on your IRB:


# sample_loop.rb

loop do

puts "You will see this non-stop" # this will keep

printing non-stop unless you hit Ctrl and c

on your keyboard"

end

IRB::Abort: abort then interupt! #this message will appear when you have decided to hit the keys that will break the loop

 

Controlling the Loop

It is not advisable to use the loop without using a break statement within the block. The infinite loop will eventually crash your system. Look at this example:


# the_helpful_loop.rb

x = 0

loop do

x = x + 1 # in the future, you can also write it

this way: x += 1. For now, let us

stick to the usual.

puts x

break # this stop the execution and stop the loop

end

The code above will only print ‘1’ on the screen. The loop stops immediately because of the break statement in the code. Understand that break will only stop the loop and not the entire program.

 

If there are lines that still need to be executed after the loop block with a break statement, the execution will continue according to the instructions of the program.

 

Now, let us try to print all the even numbers from 1 to 10 using a loop statement.


# sample_loop.rb

z = 0

loop do

z += 2

puts z

if z == 10

break # this will stop the loop

end

end

 

As you can see from the above sample, the break statement was not immediately executed until z == 10. The break took effect when the if statement evaluated to true and executed the code within the block.

 

You can use the same program to trace the odd numbers, but it is quite tricky. You need to print ‘1’ first and you need to execute it outside the loop. You also need to change the if statement that contains the break statement.

 

Before you look at the answer try to write the code on your own. You will know the answer later. First, let us look at another sample program.

 

Looking at the same program, you can also skip a particular even number and prevent it from being printed on the screen. You can do this:


# sample_loop_modified.rb

z = 0

loop do

z += 2

if z == 4

next # skips the next line if the number is 4

end

puts z

if z == 10

break # this will stop the loop

end

end

Check this out:

z == 9

As you can see, number 4 is not printed because the computer skipped the printing process for that number. The execution only resumed on the loop’s next iteration.

 

You can use a break and next to other loop construct, aside from the loop. They are regarded as Ruby’s essential loop control concepts. When you combine them with Ruby conditionals, you can start creating simple codes that bear interesting behavior.

 

Going back to the previous challenge, your code should look like this:


z = 1

puts z

loop do

z += 2

puts z

if z == 11

break # this will stop the loop

end

end

If you have initialized your variable z to 1 and still used you must have encountered an infinite loop and presses What went wrong?

 

z == 10 in your program, ctrl and c just to stop it.

You need to initialize your variable z to 1 and increment it by 2 to get the odd numbers. If you use z == 10 , then the loop won’t really stop because z will never be equal to 10. Remember that you always add 2 to the current value of z to make all the odd numbers come out. You can also use if you don’t want to go beyond 10.

 

THE DIFFERENT LOOPS

The while loop tells the computer to keep executing the code as long as the while statement or boolean expression returns true. The moment the statement becomes false, the while loop gets terminated and Ruby continues to execute the code after the loop.

 

For example, you want a program that will print the numbers 1 to10. Your code should look like this:


target_num = 0

while target_num < 10

target_num = target_num + 1

puts target_num

end

Let us explain the program line by line.

In the first line, the variable target_num has an initial value of 0.

The second line instructs the computer to keep executing the code within the while statement (the indented lines) as long as the variable target_num is less than 10.

 

In the third line, the variable target_num has a new value. The program adds 1 to its initial value 0. The variable target_num will have a new value each time it gets incremented by 1.

 

The fourth line instructs the computer to print or display the current value of target_num on the screen. It will continue to print the new value of target_num as long as target_num remains lower than or exactly 10.

 

Keep in mind that the repetition only happens within the loop and it gets terminated once the goal of the while statement has been reached or the statement becomes false.

 

If you are thinking of ways to avoid using the while statement, you are in luck because there’s another way to do it. However, after learning the long process you may want to switch back to while statement.

 

The long program looks like this:


# long_way.rb

target_num = 0

target_num = target_num + 1

puts target_num #This will print 1

target_num = target_num + 1

puts target_num #This will print 2

target_num = target_num + 1

puts target_num #This will print 3

target_num = target_num + 1

puts target_num #This will print 4

target_num = target_num + 1

puts target_num #This will print 5

target_num = target_num + 1

puts target_num #This will print 6

target_num = target_num + 1

puts target_num #This will print 7

target_num = target_num + 1

puts target_num #This will print 8

target_num = target_num + 1

puts target_num #This will print 9

target_num = target_num + 1

puts target_num #This will print 10

Is there any other way to print it? There is! Can you guess the other way to code the given program? Set your mind at work and try to find out before you look at the answer below. You can test yourself regarding your ability to code in Ruby at this stage.

 

The program with the while statement is still shorter than the two long programs.

What if the user prefers to input the number that he or she would like to print? You have no means of knowing the number that the user would type unless you have psychic abilities. You cannot simply use either of the last given programs, and it is advisable to use the while statement for this particular case.

 

Besides, even if you can guess the number that the user will choose, it would take you forever to code the program when the user types in 1,000,000.

 

Your code should look like this on the IRB:


What if the user wants to print the numbers 1 to 10 in ascending order?

IRB :001 > num = gets.chomp.to_i

10

=> 10

IRB :002 > while num >= 0

IRB :003 > puts num

IRB :004 > num = num – 1

IRB :005 > end

You can also write num = num – 1 like this num -= 1 . 

When your program keeps on printing (somewhere in your code you must have triggered an infinite loop), always press ctrl and c to break the loop. If your program is not responding, it is possible that it was caught in an infinite loop.

 

Do/While loop

The do/while loop closely resembles the while loop. The conditional check in a do/while loop is placed at the loop’s end as opposed to its usual place at the start of the loop. Take a look at the program below that display a simple do/while loop. This program can give you a better understanding of how the loop works.


# execute_once_more.rb

loop do

puts "Do it again? (Choose Yes or NO)"

ans = gets.chomp

if ans != "Yes"

break

end

end

The program prints the question and requires an input from the user. If it gets “Yes” for an answer, it will store the response to the variable named ‘ans’. The program will keep asking the question while the answer remains “Yes”.

 

The loop gets terminated once the user typed in “No” or another answer for that matter. It only recognizes “Yes” as the only response that can get the loop going.

 

It can also be written like this:


# execute_once_more.rb (another version)

Begin

puts "Do it again? (Choose Yes or NO)"

ans = gets.chomp

end while ans == "Yes"

While the other version of the sample program for do/while loop works, it's not recommended by Ruby’s creator.

 

For Loop

The for loop, in Ruby language, can be used to a collection of elements. The for loop has a definite end, unlike the while loop where it could encounter a problem. In the while loop, there is always a risk of causing an infinite loop if you are not careful in writing your code or program.

 

This is the correct syntax to write the for loop:

for z in 1 .. x do

It begins with the reserved word for followed by a variable name, in this case, z after that comes to the reserved word is followed by the range or list of elements to loop over.

 

If you need to loop over a collection of elements in a range or array, then the best choice is for a loop. In Ruby, there is a special type called range that captures a collection of elements. For example, 1..4 is a range that captures the integers 1, 2, 3, and 4. After execution, the for loop also returns a collection of elements.


# sample_program_for.rb

for z in 1..10 do

puts z

end

What if you were asked to write the same program in which the user will provide the input the extent of the range?

 

Treat this as a programming exercise for you to work on. Try to answer this on your own and you will know the answer near the end of this sub-blog. You can also use an array, something like this:


# sample_program_for.rb

b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for a in b do

puts a

end

Here are two more samples using an array:


# sample_program2_for.rb b = [123, 456, 789, 111, 222]

for a in b do

puts a

end

# sample_program3_for.rb

b = ["Chelsea", "Ana", "Charlie", "Maxi", "Gabbey"]

for a in b do

puts a

end

The for loop passes through all the values contained in the array and prints each one on the computer screen. The loop automatically stops when the last element in the array is printed. Before we discuss another sample program, here is the answer to the programming exercise that you were asked to do:

 

There are a lot of ways to loop and you need to decide which one is the best for your available data.

 

Conditionals within Loops

We want to create precise and effective loops. We can actually incorporate conditional flow control within the loops to modify their behavior. For our opening salvo for this sub-blog, let us use the if statement in a while loop.

 

In this sample program, we will introduce you to .odd? method (this and other Ruby methods can be found in Ruby documentation).


# while_with_conditional.rb z = 0

while z <= 20

if z.odd?

puts z

end

z += 1

end

In the sample program, variable z is assigned the value 0 (initialization). The while statement says that the process it contains must be executed while variable z is less than or equal to 0. However, there is a conditional if statement within the while loop. It demands that only odd numbers from 1 to 20 must be printed.

 

The variable z gets incremented by 1. When it loops over, the new value of z is 1, which is still less than 20. The loop will only stop when the variable z is higher than 20. Try the same program using .even? method instead of. odd? and see what happens.

 

Next and Break in the Conditional Loop

The reserved words break and next can be used in the conditional loop as well. When next is used in a loop, it will jump from the line where next is located to the subsequent loop iteration. The code beneath it will not be executed.


# next_conditional_loop.rb digit = 0

while digit <= 20

if digit == 5

digit += 1

next

elsif digit.odd?

puts digit

end

digit += 1

end

 

The presence of next has prevented number 5 from being printed. When the break is used in a loop, it will prompt the computer to quickly terminate the loop and prevent the execution of other code within the loop.


# break_conditional_loop.rb unit = 0

while unit <= 20

if unit == 11

break

elsif unit.odd?

puts unit

end

unit += 1

end

As you can see, the number 11 is not printed as well as the rest of the number within the range due to the presence of break. It automatically stopped the computer from executing the rest of the code or from looping.

 

Iterators

When you want methods that let you operate on each item in a collection and can naturally loop over a given set of data, then it is best to use iterators. You already know that an array has ordered list. What if you want to print the names listed in the array on the screen without returning nil? You can use the method named each.


# perform_method_each.rb

aka = ['Chels', 'Ana', 'Chai', 'Max', 'Gab', 'Allan', 'Ruth'] aka.each { |aka| puts aka }

 

The .each method loops through each item in the array starting from the very first element, which is ‘Chels’. It executes the code within the block (from the first curly brace to the last curly brace). Keep in mind that the starting and ending points of a block are determined by the curly braces ({ }).

 

Let us take a look at another sample program:


# sample_each.rb

aka = ['Chels', 'Ana', 'Chai', 'Max', 'Gab', 'Allan', 'Ruth'] count = 1

aka.each do |aka|

puts "#{count}. #{aka}"

count += 1

end

This is the output:

1. Chels

2. Ana

3. Chai

4. Max

5. Gab

6. Allan

7. Ruth

=> ["Chels", "Ana", "Chai", "Max", "Gab", "Allan", "Ruth"]

The variable count was added to serve as a counter for each name to create a numbered list output.

 

There are several iterator methods in Ruby, and you will get to use a number of them in the long run as you develop your programming skills.

 

Most Ruby programmers prefer to use iterators when they need something to loop over a group of elements. Like most Ruby programmers, you may find iterators more to your liking or you may also find other methods more acceptable than the others.

 

It’s really a matter of preference and it is best if you have a number of choices to choose from than be content with just one or two options.

 

Recursion

Ruby offers another way to create a loop called recursion. It gives the ability to call a method within itself. To make it easier to understand, let us create a program.

 

Here’s the scenario: you were tasked to create a program that must double the amount of a given number and to continue doubling the amount of each answer you obtain. For the said program, it is best to create a method like this:


def double(num)

puts num * 2

end

Then you can do this on your IRB:

IRB(main):001:0> def double(num)

IRB(main):002:1> puts num * 2

IRB(main):003:1> end

=> :double

IRB(main):004:0> double (2)

4

=> nil

IRB(main):005:0> double (4)

8

=> nil

IRB(main):006:0> double (8)

16

=> nil

IRB(main):006:0> double (16)

32

=> nil

IRB(main):006:0> double (32)

64

=> nil

You can simplify the program using recursion. We will use the same double method. You can do it this way:


IRB(main):001:0> def double(num)

IRB(main):002:1> puts num

IRB(main):003:1> if num < 60

IRB(main):004:2> double(num * 2)

IRB(main):005:2> end

IRB(main):006:1> end

=> :double

IRB(main):007:0> double(2)

 

ARRAYS

In the previous blog, you already have an idea regarding arrays and hashes. In this blog, we will try to know more about these two. Let’s say you have this kind of array named x: IRB :001 > X = [7, 'Al', 14.3, 'Claire']

 

You need to assign the array to a variable so you can do anything with it. As you can see, array x contains different types of data. If you want to print the first element of array x on the screen you can do this:


IRB :002 > puts x.first

7

=> nil

What if you want to print the next one in the list? Go back to the blog that discussed the array index if you forgot.

IRB :003 > puts x[1]

Al

=> nil

If you would like to print the last element you can do this:

IRB :004 > puts x.last

Claire

=> nil

If you need to print the other elements in the array, use an index. It is really important to practice what you have learned so that you won’t forget.

 

Nested Arrays

Nested arrays are actually arrays that contain arrays. If you would like to keep a list of the participants in each team, you can make this kind of array:


IRB :001 > set = [['Joelle', 'Vicki'], ['Anne', 'Blake'], ['Al', 'Ene']] => [["Joelle", "Vicki"], ["Anne", "Blake"], ["Al", "Ene"]]

You can use an index to access each team.

IRB :002 > set [0]

=> ["Joelle", "Vicki"]

 

Evaluating Arrays

When you need to compare the equality of arrays, you use == .


IRB :001 > x = [1, 2, 3,4]

=> [1, 2, 3, 4]

IRB :002 > y = [2, 3, 4, 5]

=> [2, 3, 4, 5]

IRB :003 > x == y

=> false

IRB :004 > y.pop # this will yield [2,3,4]

=> 5

IRB :005 > y.unshift(1) # this will yield[1,2,3,4]

=> [1, 2, 3]

IRB :006 > x == y

=> true

As you can see, the first time that the program tested the equality between the arrays it returned a false value. We need to make it true. We need to use the pop and unshift method on array y.

You already know what pop does, how about unshift? Just think of it as the exact opposite of pop.

 

ARRAY METHODS AND HASHES

There are so many array methods and this sub-blog intends to give you an introduction to some of them. You may want to keep this link handy: Array class.

 

1. include?

Does the method include? checks whether the array contains a certain argument. This method returns true or false. It is something like this:


IRB: 001 > z = [1, 2, 3]

=> [1, 2, 3]

IRB: 002 > z.include?(4)

=> false

IRB: 003 > z.include?(2)

=> true

 

2. flatten

As the name implies, flatten has the ability to turn a nested or two-dimensional array into one-dimensional. It literally flattens the array.


IRB: 001 > x = [1, [2, 3], 4, [5, 6, 7]]

=> [1, [2, 3], 4, [5, 6, 7]]

IRB: 002 > x.flatten

=> [1, 2, 3, 4, 5, 6, 7]

 

When you want to check if the content of the array has changed, simply type the name of the array and hit enter. The above program will give you this:

IRB: 003 > x

=> [1, [2, 3], 4, [5, 6, 7]]

As you can see, the array still holds its original content. You can do the same test for all the arrays that you use.

 

3. sort

The method sort is helpful when you want a sorted array.


IRB :001 > z = [4, 2, 8, 5, 3, 1, 7]

=> [5, 3, 8, 2, 4, 1]

IRB :002 > z.sort

=> [1, 2, 3, 4, 5, 7, 8]

4. product

The method product has the ability to combine arrays. It returns the combination of elements from both arrays.

IRB :001 > [4, 5, 6].product([7, 9])

=> [[4, 7], [4, 9], [5, 7], [5, 9], [6, 7], [6, 9]]

These are just some of the methods that you can use on your array.

 

The Methods Named Each and Map

The method each is usually used in for loop and it offers a simple way of performing iteration on the elements in the array. Take a look at the sample below:


samp = [1, 2, 3]

samp.each { |any_variable| puts any_variable }

1

2

3

=> [1, 2, 3]

 

The sample above is the most typical way of using each. You can also modify the items in the array and still returns the original array. Take note that you can use any variable name, but you need to be consistent in using the same variable name all throughout the program for that particular array.


samp = [1, 2, 3]

samp.each { |any_variable| puts any_variable + 3 }

4

5

6

=> [1, 2, 3]

 

The method map is similar to each, except it returns the value that the map has created. However, the original content of the array still remains the same.


another = [1, 2, 3]

another.map { |y| y*2 }

=> [2, 4, 6]

What if you use puts ?

another = [1, 2, 3]

another.map { |y| puts y*2 }

=> [nil, nil, nil]

You already know that puts returns nil. Each time the program calls upon the block, it returns nil. The methods map and each is important but because they resemble each other so much, learning them can be a tad confusing. Remember this: for iteration you need to use each, for the transformation you need to use map.

 

Hashes

The array has index and hash has keys. You already learned in the previous blog that hash entries are key-value pairs within the curly braces. Take a look at these samples:


IRB :001 > fresh_hash = {name: 'Betty'}

=> {:name=>'Betty'}

# sample 2

IRB :002 > bio = { height: '5 ft', weight: '110 lbs' }

=> {:height=>'5 ft', :weight=>'110 lbs'}

What if you want to add some more?

IRB :003 > bio [:hair] = 'blonde'

=> "blonde"

IRB :004 > bio

=> {:height=>'5 ft', :weight=>'110 lbs', :hair=>'brown'}

IRB :005> bio [:age] = 22

=> 22

IRB :006> bio

=> {:height=>'5 ft', :weight=>'110 lbs', :hair=>'blonde', :age=>22}

You can also remove an entry from the current hash.

IRB :007 > bio.delete(:weight)

=> "110 lbs"

IRB :008 > bio

=> {:height=>'5 ft', :hair=>'blonde', :age=>22}

Do you want to retrieve the information from the hash? Simply do this:

IRB :009 > bio [:hair]

=> "blonde"

You can also merge two hashes together. You can use either of these two:

# choice 1

IRB :010 > bio.merge (fresh_hash)

=> {:height=>'5 ft', :hair=>'blonde', :age=>22, :name=>'Betty'} IRB :011 > bio.merge

=> {:height=>"5 ft", :hair=>"blonde", :age=>22}

# choice 2

IRB :010 > bio.merge!(fresh_hash)

=> {:height=>'5 ft', :hair=>'blonde', :age=>22, :name=>'Betty'} IRB :011 > bio.merge!(fresh_hash)

=> {:height=>"5 ft", :hair=>"blonde", :age=>22, :name=>"Betty"}

Notice that ‘choice 1’ .merge was used and the two arrays successfully merged. When you check the current content of array bio, you will see that there’s no change. In ‘choice 2’ .merge was used with a bang operator ( ! ). When you check the current content of array bio, you will see that it has been completely modified.

 

Iterating over Hashes

Iterating over hashes is comparable to iterating over arrays, only with slight differences. We will use method each to demonstrate. However, for this program, we are going to assign a variable for the key as well as the value. We will use the variable ‘ref’ for the key and variable ‘content’ for the value.

 

You can try to create your own program using the same pattern and experiment if you want.


# iterate_hashes.rb

record = {name: 'Clark', height: '6 ft', weight: '140 lbs', hair: 'black', status: 'single'}

record.each do |ref, content|

puts "Bob's #{ref} is #{content}"

end

Recommend