Skip to main content

Lesson 2: Ruby and the Command Line

Introduction for this lesson

Objectives

In this tutorial we are going to look at:

  • what a command line is
  • how to use the command line to navigate the file system and run programs
  • what Ruby is
  • numbers and strings
  • how to use variables
  • calling and defining methods

Goal

By the end of this tutorial you will have learnt how to navigate through the command line and how to run some basic operations in Ruby.

Introduction to the command line

What is the command line?

The command line is a text interface for your computer. Similar to Windows Explorer on Windows or Finder on a Mac, it lets you navigate through the files and folders of your computer - but it is completely text based. The command line works by typing commands against a prompt, which then gets passed to the operating system of the computer that runs these commands.

How do I access the command line?

On a Mac you can access the command line by opening the Terminal application from the Applications > Utilities folder (or use cmd (⌘) + space and search for “Terminal”).

The command line can seem unfamiliar and scary, but it’s really a different way of interacting with your computer. This tutorial only covers safe commands that will not do anything bad to your computer, even if you get them wrong.

Once you’ve opened up your terminal you should see a window that has says “Last login” with a date after it, and a cursor next to a dollar sign.

Do not worry if the text in yours is a little different - it does not matter.

Basic commands are written on a single line, and run when you press the Enter button on your keyboard.

Try typing, then pressing Enter:

pwd

pwd or print working directory

The pwd command prints to the command line the current directory (another name for folder) you are in. If you have just opened up your terminal, you are probably in your “home” directory, and should get an output similar to this:

/Users/your-username

So your current “working directory” is /Users/your-username.

Getting things wrong on the command line

If you type a command that the command line does not understand, it will show you an error message. Do not panic if you see one of these - everything is fine! Take a look at the command you wrote and see if you can work out what was wrong.

Try this for example:

whargleblargle

You should see an error message like -bash: whargleblargle: command not found.

If you want to cancel your current entry, you can either delete the command using the backspace button, or press Ctrl + C to get a brand new line. Your mouse will not work for navigating around the command line commands - but you can use the arrow keys on your keyboard to move the cursor left and right.

ls or list

You might wonder “how I do know which files are in a directory?”, the ls command can do this:

ls

This should print a list of the files and folders inside the working directory. You’ll probably see directories like Applications, Desktop, Documents and Downloads.

cd or change directory

The cd command allows you to move between directories. You tell cd which directory to move to by putting the path after the cd, like this:

cd Desktop

Lots of commands need parameters like this - for example, cd needs to know the directory to move to, while pwd does not. We call the parameters “arguments”.

Task 1: change to the directory containing your code

In Lesson 1 we created a folder to keep our source code (lesson-1-html-and-css). Create a new folder for lesson 2 called lesson-2-ruby and change the working directory in your command line using cd.

Confirm you’re in the right place by running:

pwd

and check what files there are in this directory by running:

ls

There probably will not be any files because we have not created any yet.

Notes

In Finder you can copy the path to a directory by right clicking, holding down the option key (), and choosing Copy “Directory” as Pathname. Alternatively, you can drag the folder onto the terminal and it will type the path for you.

If your directory includes spaces (or other weird characters) you might need to put it in quotes so the command line does not get confused. So:

$ cd '/Users/your-username/My Directory With Spaces/lesson-2-ruby'

instead of

$ cd /Users/your-username/My Directory With Spaces/lesson-2-ruby

Introduction to Ruby

Ruby is a programming language. For a beginner, Ruby is very similar to other languages like Python, JavaScript and PHP. The basic skills you learn in Ruby will translate directly into many other languages.

As well as being a wonderful language, Ruby has a vibrant, friendly, and sometimes weird community of people. That means there’s lots of great resources for learning, and lots of places where you can get help.

Running Ruby interactively with irb

There are two ways to run Ruby from the command line:

  • Interactively with irb (Interactive Ruby)
  • Running a file with ruby itself

To start with, let’s look at irb. We’ll get on to how to run a file later.

irb is lets us write bits of Ruby and quickly see what they evaluate to.

Start irb by running:

irb

Your command line prompt will change from $ to irb(main):001:0>. You can then write Ruby code into the command line.

When you want to leave irb and go back to your command prompt type exit and press enter.

Numbers

We can use Ruby as a kind of calculator. Try typing 1 + 1 into irb and pressing enter. Do you get the right answer?

In Ruby, the + operator adds numbers together. Other operators include:

  • - - subtract
  • * - multiply
  • / - divide
  • ** - raise to the power of

You can also use brackets (()) to group things, e.g. (2 + 2) / 2 which would evaluate to 2, rather than 2 + 2 / 2 which would evaluate to 3.

Task 2: Maths challenge

Use irb to work out the answer to “191 multiplied by 7”.

Answer “` irb(main):016:0> 191 * 7 => 1337 ”`

Strings

In the real world strings tie things up. Programming strings have nothing to do with real-world strings.

Programming strings are used to store collections of letters and numbers. That could be a single letter like "a", a word like "hi", or a sentence like "Hello my friends.".

A Ruby string is written as a quote (") followed by some letters, numbers, or symbols and ended with a closing quote ("). The shortest possible string is called the empty string: "". It’s not uncommon for a single string to contain paragraphs or even pages of text.

If you type a string into irb it will return it back at you:

irb(main):017:0> "Hello IRB"
=> "Hello IRB"

Getting things wrong in IRB

Just like in the command line, if you give irb a command it does not understand it will show you an error message. Again, do not panic! Everything is fine.

irb will do its best to explain why it did not understand your Ruby, but sometimes the error messages can be hard for a beginner to understand.

For example:

irb(main):018:0> "Hello IRB" + 7
TypeError: no implicit conversion of Fixnum into String
        from (irb):1:in `+'
        from (irb):1
        from /usr/bin/irb:11:in `<main>'

Here, irb is telling us that you’re not allowed to add strings and numbers together in Ruby.

Variables

Programming is all about creating abstractions, and in order to create an abstraction we must be able to assign names to things. Variables are a way of creating a name for a piece of data.

Creating variables in Ruby uses a single equals sign - name = value. Some examples:

name = "Fido"
age_human_years = 4
age_dog_years = age_human_years * 7

This would give three variables: name with a value of "Fido", age_human_years with a value of 4 and age_dog_years with a value of 28.

Variable names in Ruby have to start with a letter, and they can not contain spaces or “special” characters like -, $, @ and &.

As a style convention, Ruby variables use underscores to separate the bits of the name - this is called snake_case (as opposed to camelCase or PascalCase which are used elsewhere).

Task 3: Set and use a variable

Use irb to set a variable called answer to the value of 7 multiplied by 6. Multiply the answer variable by 10 in irb to see what happens.

Answer “` irb(main):020:0> answer = 7 * 6 => 42 irb(main):021:0> answer * 10 => 420 irb(main):022:0> answer => 42 ”`

String interpolation

We often need to build a string out of other strings and bits of Ruby. In Ruby we can do this with “string interpolation”.

Within the string we use the interpolation marker #{}. Inside those brackets we can put any variables or Ruby code which will be evaluated, converted to a string, and output in that spot of the outer string.

irb(main):019:0> "The dog #{name} is #{age_human_years} human years old, which is #{age_dog_years} in dog years."
=> "The dog Fido is 4 human years old, which is 28 in dog years."

Note: on a Mac you can enter the # key with option () + 3

Task 4: Use string interpolation

Using string interpolation in irb, create a string with the text:

“The answer to life, the universe and everything is …”

Where ... is the value of the answer variable you set in Task 3.

Answer “` irb(main):023:0> answer = 7 * 6 => 42 irb(main):024:0> "The answer to life, the universe and everything is #{answer}” => “The answer to life, the universe and everything is 42” “`

Calling methods

While programming, we often find ourselves doing the same thing over and over again. It would be nice if we could give a particular task a name, and run it by calling its name.

In Ruby we do this with methods, and there are lots of them already built into the language. One example is rand, which generates a random number:

irb(main):025:0> rand
=> 0.11487911496307956

If we want to generate a random number less than a particular number, we can provide our maximum to rand as an "argument”:

irb(main):026:0> rand(100)
=> 7
irb(main):027:0> rand(100)
=> 43

You can also call some methods on things by using a . like this:

irb(main):028:0> "make me louder".upcase
=> "MAKE ME LOUDER"
irb(main):029:0> "em esrever".reverse
=> "reverse me"

Task 5: Decode a secret message

Decode this top secret, encrypted message:

!gniog peeK !llew repus gniod er'uoY

(Hint: it’s not Welsh - it’s been reversed)

Answer “` irb(main):030:0> ”!gniog peeK !llew repus gniod er'uoY".reverse => “You’re doing super well! Keep going!” “`