Books / Ruby for Beginners / Chapter 1
What is Runtime Environment?
Runtime environment is an important concept. The concept of “environment” itself will be introduced later, but it’s not the same thing. Runtime environment is where and “by whom” your programs will be launched in Ruby. Let’s say a qualified chemist conducts an experiment in a test tube, a big glass jar and even his or her own bath. It can be used by any “interpreter” (program-launching program) in Windows, Mac and Linux.
When the author first started with a computer, there was only one runtime environment, because there was no choice. When the computer was switched on, a cursor and the letters “OK” came on, meaning a program could be loaded. Now computers have become more intelligent, and a newbie also has to understand how to launch a program, where to enter the program text, “with what” to launch the written program and which runtime environment is best.
In fact. it is not particularly important to us which actual program the system is launched in. These days a program written in any of the popular programming languages can be launched in three OS: Windows, MacOS and Linux. Usually no changes are required in the program itself. If there are, they are minimal.
Statistics on the use of operating systems shows that the most popular one today is Windows. So we will begin with Windows, although it is not the best choice. The reason we decided to do this is to get us as quickly as possible into the run of things, so that any starting programmer can write a required program as quickly as possible. After all, setting up the runtime environment is not usually a very simple matter for beginners, and its apparent complexity may scare off a student at the first stage.
In spite of the fact that we shall begin by launching our programs in the Windows OS, we advise strongly against using the Windows for launching programs in Ruby, However, if you like, this OS can be used for writing programs. In any case, the authors recommend installing Linux as soon as possible (the Linux Mint Cinnamon edition, as the simplest installation medium), and using it. If you use Mac, there is no need to install Linux.
Terminal (also known as “console”, “shell”, “command line”) is a friend of any Ruby hacker. To run programs we’re going to build together, we need some sort of central console, a place from where these programs will be executed. Terminal is the name of this central console.
To be precise, Terminal isn’t hundred percent correct definition, but it’s often used among programmers. They say “run in terminal”, but if you dive deeper, we run all programs by a special kind of software called “shell”. In other words, we send our instructions to the shell, and terminal is just a visual wrapper around this shell, where you can configure fonts, colors, copy and paste from your screen and so on.
Looking ahead, it’s worth mentioning that there are numerous kinds of shells with slightly different flavors. The most popular is bash (name is an acronym for Bourne-again shell, a pun on the name of the Bourne shell that it replaces). However, authors of this book recommend using zsh with Oh My Zsh flavor (no need to install it right now). Zsh is slightly different from the standard one, but it’s much more convenient and gives you more flexibility.
But all the above is valid for MacOS and Linux. The standard shell for Windows is “cmd.exe”. If you click “Start”, then “Run”, and type
You’ll see the black screen and command prompt:
“Prompt” ends with
> symbol, meaning the shell is expecting your input. For the future note that every shell has its own environment and runtime settings. Some programs and commands can mess up these settings, and if you found yourself struggling with weird shell behavior, consider restarting the shell. Even experienced programmers can take advantage of this advice. You can exit the shell by typing
exit or by clicking the close button.
On MacOS and Linux terminal is available by default among other programs, and you can run it by clicking on unappealing rectangular black icon, usually with
> sign. For these operating systems shell prompt often ends with
$ symbol. It’s not always true, but keep in mind that if you see dollar sign somewhere in documentation or book, and command goes right after this sign, you don’t need to type the dollar sign. For example:
For the code block above type
ls only (
dir if you’re on Windows). This command will show the list of files in current directory.
Regardless of operating system you’re using, type
ruby command in your terminal and press “Enter”. In case of MacOS and Linux you will not see any error, Ruby will start and will be silently awaiting for your input. On Windows you most probably see “Bad command or file name” error message. It just means that Ruby is not installed by default on Windows, and we need to install it first.
Let’s take a step back. Now and in the future if something is not right, google it. For example, google “How to run Ruby program on Windows” if you have difficulties running your Ruby program. Good question is half the battle. And to be honest, you can only learn to program if you can ask good questions: just think consistently and follow a logical pattern.
For running Ruby programs in Windows you will need to run Ruby Installer and follow instructions. After that
ruby command should be available in your terminal. Let’s run
ruby -v to see the version of installed Ruby (here and below commands should work on both Windows and Macs):
$ ruby -v ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin16]
If command above doesn’t work, try restarting your terminal. Let’s run
ruby again and write your first program. When you type
-v) in the terminal, it will be silently awaiting for your input. Just type
puts 1+1 and hit Ctrl+D (sometimes you need to do it twice):
$ ruby puts 1+1 (hit Ctrl+D here) 2 $
So what do we see on the screen above? Command prompt
$, then we type
ruby. Ruby is silently running and awaiting for our input, we type
puts 1+1, after which we hold
Ctrl key and hit
D on our keyboard (it serves as “End Of Input” signal) and we have our program executed!
2 on the screen is the result.
Let’s dive a little bit deeper into what had happened above. When you typed
ruby your shell executed Ruby interpreter - a special program to read and run your own, human-language programs. So
ruby is just a program to run your programs.
Combination Ctrl+D (also denoted as ^D below) will be useful in your further software engineering career, and it just means “end of my output”, “I’m done here”, “now it’s your turn, smart computer”. Your terminal send a byte with the code 4 (you don’t need to remember that) and Ruby understands there won’t be any keystrokes anymore and now it’s a time to execute what a user has just typed.
puts 1+1 is your first program! Congratulations on that! Unfortunately we didn’t save it on the disk, because we typed it from our keyboard and it disappeared right after it was executed. But it’s not a big deal, your first program was only 8 bytes, and you can always type it again, if you want to.
But what exactly does
puts 1+1 do? Before we answer this question, here is exercise for you. Try to run just
puts. What happened? We don’t see anything on the screen. Actually, calculation has completed successfully, but result wasn’t put back. It’s possible when you give a long-running task to a computer, such as a set of complex calculations, the result will never be printed because you missed typing in
In other words,
puts just shows result on the screen. It’s a combination of words “put” and “string”. There are other, but similar commands in other computer languages to put results on the screen. For example in BASIC you need to type
printf (you can also do
printf in Ruby!).
But why do we keep
puts at the very beginning? In fact, we need to sum up two numbers first, and only after that we need to print result on the screen. Programmers say “method (or function) accepts parameter”. So, in other words, want to “put string”, and this string is going to be
1+1. This is our parameter. Can you see how we just split this line into two parts?
Ruby offers alternative syntax for this line, which is little bit more illustrative:
Like in math language we calculate numbers in parentheses first, and then do the rest. The same rule applies to computer languages.
There are few basic math operators that you can use in Ruby:
+to add numbers. For example:
1 + 1
-to subtract numbers. For example:
5 - 2
/to divide one number by another. For example:
120 / 12
*to multiply. For example:
2 * 5
Exercise Without looking to solution below, try to write a program that calculates the number of milliseconds in one day. How would you approach this problem? How many hours in one day? How many minutes in one hour? How many seconds in one minute? How many milliseconds in one second?
Here is the answer to exercise above:
$ ruby puts 60 * 60 * 24 * 1000 (hit Ctrl+D here)
This is a purely math problem: multiply the number of seconds in one minute by the number of minutes in one hour. Then multiple it by 24 hours in a day. And after that by 1000 in order to get milliseconds instead of just seconds. Pretty straightforward, isn’t it?
Now let’s write a Ruby program to calculate this expression:\[5^5 * 4^4 * 3^3 * 2^2 * 1^1\]
For the power function in Ruby you have to use
**. For example,
5 ** 3 is
5 * 5 * 5 and it equals
125. So the Ruby program is as follows:
puts 5**5 * 4**4 * 3**3 * 2**2 * 1**1
It’s hard to believe, but the result of this operation is exactly the same as in our previous example: the amount of milliseconds in a day! Both programs will produce
86400000. There is no any explanation to this, just a fun fact. As exercise, try to run the following program and guess what is going to happen?
puts 60 * 60 * 24 * 1000 == 5**5 * 4**4 * 3**3 * 2**2 * 1**1
Hello, I’m Your Ruby REPL
With the case of
1 + 1 program from previous chapter, interpreter performs two actions: read (R) and evaluate (E). We had no “print” action (
puts in our case), so there was no any result on the screen. In other words, to see results we need to perform three actions:
- Read (R)
- Evaluate (E)
- Print (P)
It would be also nice if we could avoid running
ruby command from terminal every time, so we can execute programs in constant loop (L). It turns out this functionality is already there! REPL acronym stands for Read Evaluate Print Loop.
It’s very similar to Ruby interpreter, but accepts Enter key as the end of your program. Instead of exiting on Ctrl+D (end of input), it just starts reading the input again. REPL is pretty well-known definition, and not tied to the Ruby language infrastructure. Other languages have their REPLs too. Ruby’s REPL called
irb. You can type this command from your shell:
$ irb 2.5.1 :001 >
Weird numbers at the beginning of the line is just the Ruby version (2.5.1). The same output is for
ruby -v command.
001 indicates the first string. In the future you’ll see how you can type multi-line mini-programs to REPL. Since REPL acronym already contains “Print” word in it, you don’t have to type
puts. Whatever you do, result will be printed on your screen.
Exercise Calculate the number of seconds in a day, inside of a REPL without using
Principle of a least surprise says that to exit REPL you should type
exit. Let’s do it… And it works!
We would like to point out that authors rarely use default
irb as a REPL. There is a better alternative called Pry. It has the same functionality, but offers more flexibility and configuration (to be discussed later in this book).
Running Ruby Programs From a File
Running a program from a file isn’t too much more difficult that running it from a terminal. You just pass argument to a Ruby interpreter with a file name:
$ ruby app.rb
In the example above interpreter will read a program from a file
app.rb, and execute it the same way as it would be executed if you typed your program to Ruby and pressed Ctrl+D.
But the question is, where and how one should save this program, where to type it, which code editor you should use? Let’s answer the first “where” question, because answer implies that student is familiar with file system. But there could be some traps and pitfalls.
If you use Windows, consider installing Linux Mint Cinnamon edition1 as soon as you can. If you’re on Mac, you don’t need to do anything special.
On Windows we will need to create a folder (or “directory”) on disk C: and name it “projects”. On Mac and Linux we’ll need to create this directory inside of home directory. After that we’ll need to switch to this directory, create a file there, and run this file.
In other words, at this point of time you need to know how to do four things:
- Create directory
- Change directory (switch to directory)
- Create a file in directory and put some text content to this file
- Run this file (we know how to do that already:
Here we could give you some Linux/MacOS commands and quit explaining Windows, but market has different opinion. Statistics show that at least half of our readers are using Windows. We hope you’ll follow our advice and install Linux (again, no need to install Linux if you’re on Mac), but we’ll give you brief details of each operating system, including Windows. Just keep in mind that it’s absolutely impossible to be a good Ruby hacker on Windows.
Skill of navigating the file system is crucial for any programmer. Like a librarian should know the location of every book in the library, programmer should know how to navigate the file system, how to search files, create, copy, and delete files. You should have a picture of the file system you’re working with in your head.
But in practice, it’s been found that most of the students don’t have a good understanding, and the right skill to navigate and work with a file system. We could give you a list of essential commands and ask to remember the list, but the more humane way is to actually explain, give options, details, and let you know about the tools that can help you on your way. So let’s spend some time on learning a file system, and get familiar with a file manager.
Linux Mint Cinnamon is free Ubuntu Linux based operating system, recommended by book authors as the most friendly and intuitive. ↩