Ruby Tutorial: Introduction. Preparations. Variables. Data types Overview. Comments.


Доступно на русском языке

Introduction

As long as you've already decided to read this tutorial, I will not spend your time describing what Ruby is, when this language has emerged, who was its creator, what pros and cons does Ruby have. I'll note, however, that it is not a very simple language. Programms written Ruby may be self-explaining and easy to understand, but at the same time they may be convoluted and messed up - it depends on the programmer's skill. Ruby has a bunch of special concepts and idioms - after all, he was partly inspired by Lisp, a family of functional programming languages. Still, having mastered this article, you'll understand that the program does not to be huge: Ruby programs are often and succinct and expressive. Moreover, you will also be able to start learning Rails, a great web framework that has become tremendously popular for the past years. I, on my side, will do my best to help you dive into the world of Ruby and make the journey interesting and useful. Let's get started then!

Please note! This tutorial is distributed under the Creative Commons Attribution-ShareAlike 3.0 license on the website bodrovis.tech. Copying of materials is allowed but you must attribute the work in the manner specified by the author. If on some resource you had to pay money to read this tutorial, I highly recommend demanding a refund and notifying me about this incident. Thank you for your cooperation.

Meet the Author

My name is Ilya, I'm IT specialist ane web programmer with more than 8 years experience. I've created many dozens of articles, screencasts and courses for websites such as Sitepoint, TutsPlus, Eduonix and others. I give personal programming lessons for people all over the world, work as a teacher in Moscow Aviations University, I freelance and participate in Open Source projects. I really love helping people and share my knowledge therefore I decided to write this Ruby tutorial.

Helpful Links

Preparations

For this tutorial I'll assume you are using Ruby version 2 or higher (at the time of writing the latest version is 2.3.1). Ruby's install information can be found at the official website; it also lists a hanful of Ruby version managers (like RVM, uru etc). These managers are used to easily switch between different Ruby version on a single PC. Still, you don't need to install a manager to prepare for this tutorial. A special note for Windows users: Отдельное замечание для пользователей Windows: you'll need to use the RubyInstaller and additionally install Development Kit (choose the suitable version from the list at the bottom of this page). Development Kit's installation instructions are available here. To put it simply, Development Kit is used to compile certain C/C++ libraries on Windows.

Talking about code editor, you may use anything starting from a basic Notepad, though it's better to stick with an option that offers code highlighting. Here are a couple of possible options:

  • Notepad++ (it's a very simple and convenient solution supporting dozens of programming languages);
  • vim (many seasoned programmers prefer it);
  • Sublime Text 2;
  • You may also go for an integrated development environment (IDE), like Aptana Studio, Komodo, RubyMine and others, but would not recommend doing so. IDEs are great for large projects (for example, built with Rails), but for now to stay away from them as they may be too complex and resource-intensive for small tasks.

Git Version Control System (Additional Section)

Creating more and more complex projects, you'll surely require some tool to store different versions of the code. Of course, you may simply create files like my_file.rb my_file_backup.rb my_file_2016.rb my_file_new_2016.rb, but it's too easy to get lost with this technique. That's why version control systems were invented, and Git - is one of the most popular among them (especially among Ruby developers). This course is not aimed at detailed discussion of Git (though on its main site you can find a very detailed guide), therefore let's simply remember that version control system allows us to track changes made to the project, navigate between those versions and undo incorrect changes.

To start working with Git, you need to install the client suitable for your OS. Then perform those two commands for the first-time setup:

git config --global user.name "Name"
git config --global user.email email@example.com

This way you identify yourself; your name will be visible in the version history. Next navigate to a directory using the cd command and say

git init

to start tracking changes. The next command

git add -A

adds all your files into the Git repository (storage).

git commit -m "Initial commit"

means that we want to retain (apply) the changes. The -m option sets the message that will then be visible in the version history. Try to set helpful messages so that navigating history is easier.

On top of that you can publish your project in the Internet, for example to request help in solving a problem or to demonstrate your skills for a potential employer. There are two popular website compatible with Git: GitHub (de-facto standart for many Ruby devs, a very popular resource built) and BitBucket (it's advantage is the ability to create private repositories free of charge, whereas on GitHub you'll have to pay for this feature). Registration on both sites is very simple and the setup guides can be found here (GitHub) and here (BitBucket).

Having performed all the necessary manipulations and created the new repositary (repo), you can publish the changes by typing

git push

GitHub and BitBucket offers additional tools like wiki-pages (for example, to host program's documentation), issue tracker, statistics and some others. You don't have to use one of these sites to successfully finish this course, though I do recommend spending some time to research them. They are not complex, believe me.

Working with the Terminal

Ruby programs are booted from the command line (terminal). Of course, you may use a basic terminal available in your OS, but I really encourage to use tmux (terminal multiplexer) for Linux or ConEmu for Windows. These solutions allow to boot multiple terminals in the same window which is very convenient.

To boot a Ruby program say

ruby my_file.rb

ruby is the name of the command, whereas my_file.rb is the file containing our program (note the .rb extension that stays for "Ruby").

On top of that there is an interactive Ruby console (dubbed as IRb) available. It can be opened by running the following command:

irb

IRb is like a sandbox where you can run Ruby instructions on the fly, observing the result. This tool is very convenient when learning new concepts.

Variables, Data Types, Comments

Ruby is a programming language that uses dynamic typing with a funny name "duck typing". This name comes from a saying: "If something is quacking like a duck and looks like a duck, then most likely it's a duck". Wikipedia explains that duck typing "is concerned with establishing the suitability of an object for some purpose. With normal typing, suitability is assumed to be determined by an object's type only. In duck typing, an object's suitability is determined by the presence of certain methods and properties (with appropriate meaning), rather than the actual type of the object".

The first and foremost fact to remember is that you don't need to explicitly define variable's type when initializing it, like it's done in C or Java. It means that the following program

new_string = 'my string'

is absolutely correct. Here we are creating a new variable called new_string and assign it a string value of 'my string'. Later we will learn that variables have different scopes but for now let's put it aside. Also note that Ruby does not have any main procedures (like in C#, for example), therefore we just created our first one-line program!

By the way, let's try to give our variables useful names (a, b, c are not really useful), write them in lowercase with words separated by underscores _. This naming technique is called "snake case" (because underscore resembles a snake) and is used by many Ruby programmers.

Now let's list Ruby's data types. Most of them are quite common and are used in other programming languages, however you may be dazzled by some others. Don't worry - we will discuss each of them in the next parts.

  • String
  • Numbers
  • Booleans
  • Arrays
  • Hashes
  • Symbols

In the code listing above we have created a string variable. Still, we are free to assign it a new value, for example boolean:

new_string = 'my string'
# more code
new_string = false

This is not an error, though it's not recommended as we don't want to introduce unnecessary complexity.

Comments

Note the line # more code - this is a single line comment, which starts with a sharp symbol #. Commenting your code (especially for the complex parts) is a good practice; this becomes even more important when working in a team. Comments can be multiline as well. Such comments are useful when you need, for instance, to document a method.

=begin
Anything can be written
between begin and end.
This is an example of
a multiline comment.
=end
new_string = 'test'

All lines between the =begin and =end keywords are comments and won't be interpreted. Line 7 is not a comment - it's a code that defines a new variable. Note that it's best to write comments in English, especially for projects that you publish to services like GitHub or Bitbucket - this way your code can be better understood from people all over the world.

Conclusion

So, in this introductory lesson we discussed the steps necessary to prepare for the course, wrote our first Ruby program, had a look at data types and learned about comments. In the next part we will discuss data types in more detail and craft a couple of other Ruby programs. See you there!

Want to know more? Need help? Enroll for the private lesson now and I will get back to you in the next 24 hours! Together we will surely solve your problem :).

Follow me on Twitter to get updates about new articles >>