rubyisforfun/manuscript/009.txt
Roman Pushkin 845b6a57eb Save
2018-12-23 01:08:11 -08:00

108 lines
No EOL
8.6 KiB
Text

## Setting Up Windows (MacOS, Linux) For Your First Program
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](https://ohmyz.sh/) 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 `cmd.exe`:
![Run cmd.exe in Windows](images/009-run.png)
You'll see the black screen and command prompt:
![Windows shell](images/009-cmd-exe.png)
"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:
```
$ ls
```
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. If you can't conquer the problem by yourself, ask your question on [StackOverflow](https://stackoverflow.com), but keep in mind it is the place where you can ask a very "precise questions" about something.
For running Ruby programs in Windows you will need to run [Ruby Installer](https://rubyinstaller.org/) 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 `ruby` (without `-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 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.
Command `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 `puts 1+1` does? Before we answer this question, here is exercise for you. Try to run just `1+1`, without `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, some type of complex calculations, and result will never be printed because you've missed out `puts`.
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 `print`, in C programmers often use `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:
{title="Ruby program to sum up two numbers and passing result of operation to 'puts' function as parameter:", lang=ruby, line-numbers=off}
```ruby
puts(1+1)
```
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`
X> ## Exercise
X> 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:
{title="Ruby program to calculate math expression mentioned above:", lang=ruby, line-numbers=off}
```ruby
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?
{title="Try to guess what will be printed on the screen?", lang=ruby, line-numbers=off}
```ruby
puts 60 * 60 * 24 * 1000 == 5**5 * 4**4 * 3**3 * 2**2 * 1**1
```