Learn Ruby | Introduction
Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.
Today I am going to start my first ever series on Steemit and this is gonna be about Ruby. I have decided to choose this language because I haven't seen many tutorials on Ruby and I thought this will be a great opportunity to start my own series in which you will learn everything that you need to know about Ruby. The above quote is taken from Ruby's Official Website.
Repository
Other relevant repositories
What will I learn?
This tutorial will help you get started with Ruby and you will learn these things in this tutorial.
- Learning about Ruby
- Learning what we can do with Ruby
- Installing rbenv (Ruby Virtual Environment)
- Installing Ruby-Build (And some Libraries)
- Installing Ruby
- Learning about each data type of Ruby
- Learning how we can create variables
- Learning how to get input
- Creating a simple application that adds numbers and then prints it
Requirements
- A working modern computer running macOS, Windows or Ubuntu
- Basic understanding of using the code editor
- A will to learn Ruby
Tutorial Content
Learning About Ruby
Before we go any further I would like to explain what Ruby actually is because without knowing what Ruby is we can't understand it properly. We all know that is a programming language. Ruby is one of the easiest and effective languages to learn right now.
It is a general-purpose language like Python. I will not go into the history of it because it doesn't matter, what matters is that what it is used for because you don't want to waste your time to learn a language for which you don't have a passion for. Because of a famous framework that is known as "Ruby On Rails", it is mostly used in making web applications. You can literally make a web blog in Ruby in just a few minutes. Ruby itself is an object-oriented scripting programming language. The scripting language is a language that is directly executed without compiling.
What can you do with Ruby (not using frameworks)
- Creating Command Line Tools
- Creating Simulations, explorations and general R&D
- Creating Programming Support Packages
- And much more complex things!
Installing rbenv (and other small things!)
Now that we have learned about Ruby, let's actually jump right into it but first we will need to install Ruby itself. If you are on Windows you can just download the Ruby from here. Download the Ruby installer, install it normally and skip all these installations. If you are on Linux like me then you will need to install rbenv, which we are going to use for creating Ruby virtual environments and this will allow us to install multiple versions of Ruby at the same time.
To install rbenv we will first need to clone the Github repository of rbenv. So open the terminal and type git clone https://github.com/rbenv/rbenv.git ~/.rbenv
and this will clone the rbenv. If you don't have git installed then a message will appear on terminal saying that you need to install git, just copy the code and run it and git will be installed. After cloning the rbenv, type echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
and then type echo 'eval "$(rbenv init -)"' >> ~/.bashrc
. In the end, just type source .bashrc
. The rbenv has now been installed.
Installing Ruby-Build
Now that we have installed rbenv, let's move on and install Ruby-Build which is a command-line utility that makes it easy to install virtually any version of Ruby. To install Ruby-Build, type this in terminal git clone https://github.com/rbenv/ruby-build.git "$(rbenv root)"/plugins/ruby-build
and it will clone the GitHub repository of it.
Now lets our directory in terminal to .rbenv, to do this type cd .rbenv
and this will take you to that directory in terminal. Now type git pull
just to make sure everything is up to date. If it is not then it will be updated automatically and if it is then a message will show up saying that everything is up to date. Now you can go back to the root directory by typing cd
.
Installing Ruby (And some external libraries)
Now is the moment we were all been waiting for. Now that we have installed all the necessary things, type rbenv install -l
by the way that is small L (l) and not 1. Now Ruby should be installed. We are ready to start using Ruby but before we should install some external libraries to compile the code. To install it, type sudo apt-get install -y curl gnupg build-essential
. Now type sudo apt-get install -y libssl-dev libreadline-dev zlib1g-dev
and this will install another library. You don't have to understand these commands because you can just copy-paste them and most people don't even know what they are doing. Now I am going to install another version of ruby and you can do this by typing rbenv install 2.4.2
and now, at last, we are going it to make our default version. We can do this by typing rbenv global 2.4.2
. Now we have successfully installed Ruby and you can check it by typing ruby -v
. If it shows the version then that means that it is installed successfully.
Creating our first Ruby file and executing it
All the ruby files have ".rb" extension. So to create a ruby file, go to the directory in which you want to create the file and then create a file with the extension ".rb" you can name the file anything you want as long as the extension is correct. Now open it with any code editor, I will be using Sublime Text because it allows multi-editing and I really like that but you can use any code editor you want. Let's start with something very basic. The first thing to learn is "print" command and what it does is that it prints whatever you assign to it.
In the previous sentence by "print" I mean showing so if I type print "Hello World"
it will show Hello World on the command line when we run the file. Type print "Hello World"
and then save the file and open the terminal on Linux or cmd if you are on Windows and the change the directory to wherever the file is located. You can do this by typing "cd" on terminal and cmd as well, I won't go in detail of commands but typing cd Ruby
will change the directory to "Ruby" folder (That's the name of my folder). Once we are in the directory we can run the Ruby file by typing ruby Ruby_App.rb
. After "ruby" type the file name, in my case the name of the file is Ruby_App.rb. Now you know how you can execute the Ruby file so I won't be repeating this process again.
Actually Learning Ruby
Data Types
Before we jump right into practical stuff, let's some fundamentals of Ruby. There are six types of data in Ruby. Those six data types are
- Arrays
- Boolean
- Hashes
- Numbers
- Strings
- Symbols
Now it's time to learn about each of them. I know it's boring but it is needed to fully understand Ruby. So let's start learning about each data type one by one.
Arrays
Arrays in Ruby are ordered collections of objects. They can hold any objects (arrays, boolean, hashes, numbers and other data types. They can also hold another array). An array is also a list of variables enclosed in square brackets and separated by commas. I know some of you may be a little confused here so let me try to explain the arrays with an example.
["red", "blue", "green"]
Above is an array. There are three objects in the above array and they all are strings (we'll learn about them later). The indexing of the array always starts from zero (0) so the index of the red in the above array is 0, the index of blue is 1 and so on. A simple way to create an array is this
colors = ["red", "blue", "green"]
In the above line of code, we have created an array named "colors" and that array contains three objects and those objects are "red", "blue" and "green".
Booleans
In our code, we have to use booleans from time to time. We make our code make a lot of decisions based on true or false. True is an instance of TrueClass and false is is an instance of FalseClass. In Ruby there are four main boolean operators and list is given below.
Boolean Operators
- ! (“single-exclamation-mark”) which represents “NOT”,
- && (“double-ampersand”) which represents “AND”, and
- || (“double-pipe”) which represents “OR”.
- == (“double-equal-sign”) which is for comparing two values
Let me explain how each boolean operator works more briefly.
! (NOT)
The first boolean operator is "not". Take a look at the code below
!true #=> False
What do you think it will return true or false?
If your answer was false then give yourself a pat on the back because that's the correct answer but no need to be that happy because it was just an easy question. If something is not true what it would be? False!
So this was you can use "!" boolean operator in your code.
&& (AND)
In Ruby, double ampersand represents "and" and requires both values to be true to make the whole statement true. Take a look at the code below
1.is_a? Integer && 2.is_a? Integer #=> True
The above statement as a whole is true and let me explain why. At the left side of the double ampersands, we are checking if 1 is an integer or not and surely 1 is an integer. One the right side of the double ampersands, we are checking if 2 is an integer or not and surely 2 is an integer. When both sides return true then this statement as a whole is also true. If anyone side is false then a statement as a whole is false too.
|| (OR)
In Ruby, double pipes represent "or" and require one of the value to be true to make the whole statement true. Take a look at the code below
1.is_a? Integer || "a".is_a? Integer #=> True
The above statement is true because one of the value is true. Even though "a" is not an integer (it is a string), on the other side 1 is an integer which means the whole statement is true because one of the value is true.This is getting harder to explain :p
== (Equal)
In Ruby, double equal to sign represents Equal. It is also known as comparison operator because it is used to compare two values and if both values are equal then the statement is true, else it is false. Take a look at the code below.
number = 1
number == 1 #=> True
In the above code, first of all, we are creating a variable (you will learn about them later) but basically, we have stored 1 in the variable known as "number". Then we are comparing the number variable with an actual number and it will return true because both have the same value but if the variable would have contained a string (you will learn about them later) and you compared it to an integer then it will return false.
Other Comparative Operators
There are also some other operators that you can use to compare values and you can learn about them from the image below.
Hashes
Hash is a collection of keys and each key holds a value. They are very similar to dictionaries in Python. Each pair in the hash has an identifier that identifies which variable of the hash we want to access. We can create a hash by just typing two curly brackets ({}) when declaring a variable. Example
member_ages = {}
By the above code, we created an empty hash. Now let's add some key-value pairs to this hash. Take a look at the code below.
member_ages = {
"William" => 31,
"Andrew" => 25,
"Smith" => 23
}
In the above code "Willaim", "Andrew" and "Smith" are the keys and there are values assigned to each key and in our case, the value for each is the age of the key. For example, the age of the William is 31.
Numbers
This is one of the easy data types to explain. We all know what numbers are, in Ruby there are two types of numbers. One is Integer while another one is a float. An integer is a number that does not have a decimal point i.e 5. A float is a number that has a floating point i.e 5.1. There are also two subclasses of Integers and that are Fixnum and Bignum but you don't have to worry about them.
Strings
In most programming languages, a string is a text and that is the same case in Ruby. A string is an object that represents a text and that text could be anything. Even though to us that text holds meaning. There are many ways to define a string but most common way through double-quotes (" ") and single-quotes (' ').
Symbols
A symbol is similar to String but a symbol can’t be changed. It is represented as both string and number and it is written like this :word
. A symbol can never be changed once it is created. You may be wondering why do people use Symbol. Symbols are better for performance so whenever you use a string, every time the string is a different object. To us, it is the same word but to the computer, it is different every time. The case is different with symbols, the symbols are always the same.
A Tip!
If you ever don't know the data type of an object just print the object with .class after it like done below.
"Hello".class
Doing this will return the class of the object which is also known as a data type.
Creating a Variable
Now that was a lot to take in all at once but let's come to the practical stuff now. You can also create variables in Ruby just like in other languages. A variable is a way to keep data in a word but that word is not a string. Take a look at the code below.
my_name = "Driplo"
In the above code, we are creating a variable called " my_name" and assigning it the value of "Driplo". There is one thing to note in the above code the word Driplo is a string and it is always in quotation marks (" ") just like we learned. We can also print the variable by typing print my_name
and this will print "Driplo" because that was the data we assigned to it.
Getting The Input
Now we are going to do something a bit fancier but very basic and that is to get the input from the user. Getting input from user is very easy in Ruby. To do it we use "gets" function. Take a look at the code below to learn more.
print "Enter Something: "
word = gets
So what above is going to do is first print the statement "Enter Something: " and then allow the user to enter something. The "something" that the user entered is saved into a variable called "word". We can also improve it by doing something like this.
print "Enter a value: "
value = gets.to_i
Now it will tell the user to enter a value and once the user enters a value it is saved into the variable called "value" but not only that the value that is also converted to an integer.
Creating a simple application
Before I leave you with this tutorial, I just want to help you create a simple application that first asks for two values and then adds them both and then print them. Making this application will review everything that we learned up to now. First of thing that we need to do is to get two inputs and you already know how to get them so try to do this part by your own but if you are stuck just take a look at the code below and see what are you missing.
print "Enter first value: "
value1 = gets.to_i
print "Enter second value: "
value2 = gets.to_i
There another way that we can output data and that is "puts". The difference between both is that print will not put a new line after the statement while puts will put a new line after the statement. So here is how we will output data using puts
puts value1.to_s + " + " + value2.to_s + (value1 + value2).to_s
In the above statement first, we are outputting data using puts. We are converting value1 which is the first input that we got from the user and then converting it to string. There are a few basic things that you need to understand. Integer An integer be added to another integer like 5 + 5 is equal to 10. A string can only be added to another string. So adding "Hello" + "World" will result in "HelloWorld". If you need to add a space between them then you can do something like "Hello" + " " + "World". So we created the value1 to a string so we can add them and then added them with the string " + " so if the input by the user was 7 then it will return "7 + " (without quotation marks). Now we are further adding value2 to the statement after converting them to string and then, at last, we are printing the result of value1 + value2 to the screen. The full code for this application is.
print "Enter first value: "
value1 = gets.to_i
print "Enter second value: "
value2 = gets.to_i
puts value1.to_s + " + " + value2.to_s + (value1 + value2).to_s
End
This was a long tutorial and I hope you learned something from it. To summarize things, first we learned how to install Ruby and some other things. Then we learned about data types in Ruby. We learned how we can create variables and get input from user and at the end we built a simple application. Stay tuned for the upcoming parts of this series and if you have any question kindly leave them in the comments.
Thank you for your contribution.
This moderation might not be considered due to the below:
Try to come up with new and more innovative/useful ways to utilize ruby.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
Hi @portugalcoin , since I'm new here, you got me thinking. As I wrote already in my introduction post, I'm a student/developer and besides Ruby I also know some Python. But because I saw some extremely well-written Python tutorials, I figured "let's not go the Python route, that's already been covered". But because you said that the topics I covered in this Ruby tutorial were already covered elsewhere on the internet (in the docs) I've now come to the conclusion that it doesn't really matter if Ruby wasn't covered too much on Utopian because it's already covered elsewhere on the internet. So with that in mind, maybe it's better for me to scan for more advanced Python-related topics to write tutorials on, since I know a bit more about Python than about Ruby. What do you think about it?
Congratulations @driplo! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :
Award for the number of upvotes received
Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word
STOP
Do not miss the last post from @steemitboard:
SteemitBoard World Cup Contest - France vs Belgium
Participate in the SteemitBoard World Cup Contest!
Collect World Cup badges and win free SBD
Support the Gold Sponsors of the contest: @good-karma and @lukestokes
Congratulations @driplo! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :
Award for the number of upvotes received
Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word
STOP
To support your work, I also upvoted your post!
Do not miss the last post from @steemitboard:
SteemitBoard World Cup Contest - France vs Belgium
Participate in the SteemitBoard World Cup Contest!
Collect World Cup badges and win free SBD
Support the Gold Sponsors of the contest: @good-karma and @lukestokes
Congratulations! Your post has been selected as a daily Steemit truffle! It is listed on rank 11 of all contributions awarded today. You can find the TOP DAILY TRUFFLE PICKS HERE.
I upvoted your contribution because to my mind your post is at least 12 SBD worth and should receive 101 votes. It's now up to the lovely Steemit community to make this come true.
I am
TrufflePig
, an Artificial Intelligence Bot that helps minnows and content curators using Machine Learning. If you are curious how I select content, you can find an explanation here!Have a nice day and sincerely yours,
TrufflePig
Congratulations @driplo! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :
Award for the number of upvotes
Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word
STOP
Do not miss the last post from @steemitboard:
SteemitBoard World Cup Contest - Croatia vs England
Participate in the SteemitBoard World Cup Contest!
Collect World Cup badges and win free SBD
Support the Gold Sponsors of the contest: @good-karma and @lukestokes