Preparations

Installing Ruby

For the purposes of this book, you'll need to have Ruby and RubyGems installed on your machine. You will need Ruby version 1.9.3 or greater. We prefer at least Ruby 2.0.

If you are working on a Mac or Linux machine, you should have Ruby installed already. Go to your command line or terminal application and enter ruby -v. You should see a print out of the version of Ruby that is installed on your machine. Some system Ruby installations, especially on Mac, have limited permissions and will impede your ability to install gems, upgrade Ruby, and perform other development tasks. Therefore, even though your system comes with Ruby, you still need to install Ruby again. If you refer to the official Ruby installation documentation, you'll see that there are 4 choices:

  • rvm
  • rbenv
  • Homebrew (Mac only)
  • Build from source

If you're technically inclined, you can try rvm or rbenv. These are Ruby version managers that allow you to run different versions of ruby side by side, and allows you to switch between them freely. Don't use rvm or rbenv if you aren't proficient from the command line and can't debug installation issues on your own. Building from source is also not a good idea for beginners. That leaves Mac users with one choice: install with Homebrew.

If you are on a Windows machine, we recommend using RubyInstaller to install Ruby. We also recommend installing DevKit from the same site.

RubyGems comes with Ruby 1.9.3 and higher, so once you have Ruby installed you can verify from terminal with gem -v. You should see a print out of the version of RubyGems you are using.

Before you begin, make sure to verify that typing in ruby -v in your terminal returns version 1.9.3 or higher.

Using a Code Editor

You'll be using a code editor to write code. A code editor is used to create plain text documents with no styling or formatting. If you already have a favorite code editor (e.g., Vim, TextMate, Emacs, Notepad++, etc.) you can use it to work through this book. However, if you do not have a preferred code editor, we recommend using Sublime Text. It's not free, but you can use it for free as long as you'd like (every now and then a pop-up notification will ask you to purchase a license). Sublime Text is a great code editor that is powerful, fast, and used by many professional Ruby developers. It is also quite easy to learn and works well out-of-the-box.

Another new entrant in the editor space is Atom. The great thing about Atom is that it's open source and completely free to use and modify. It was originally created by Github and already has a growing community of users and packages. There are installation packages for Mac (OS 10.8 or later), Windows (7 or later), and Linux. It's pretty new, and not quite as fast or stable as Sublime Text, but it has a lot of potential.

Note: avoid using word processors or advanced text editors. These software applications are built for writing, not coding, and often inject invisible characters or whitespace into the document. While that helps the text look nice, it can cause bugs or unexpected behavior when you copy/paste from word processing software.

Stylish Ruby

The Ruby language has specific stylistic conventions that make reading and writing Ruby code easier for everyone. These are things you should adopt as quickly as possible, otherwise your code will stand out like a sore thumb.

  1. Your text editor's tab function should be set to 2 spaces and indenting should be set to use spaces.

  2. When you see the # sign at the beginning of a line, that means anything after it, on the same line, is a comment. Comments are used by programmers to leave notes for other programmers or themselves at a later point in time.

  3. When you define or initialize a method, variable, or file, you should always use snake_case formatting. snake_case formatting is created using all lower case letters and separating words with the underscore character.

    # Naming a file
    this_is_a_snake_cased_file.rb
    
    # Assigning a variable
    forty_two = 42
    
    # Defining a method
    def this_is_a_great_method
      # do stuff
    end
    
  4. When you want to represent a value that will not change in your Ruby program, you define a constant variable, often referred to as a constant. In Ruby, constants are denoted with all uppercase letters.

     # Constant declaration
     FOUR = 'four'
     FIVE = 5
    
  5. When working with do/end blocks, prefer { } when the entire code expression fits on one line.

      # Multi-line
      [1, 2, 3].each do |i|
        # do stuff
      end
    
      # Does the same thing in single line
      [1, 2, 3].each { |i| # do stuff }
    
  6. The last style convention you'll need to learn at this point is how to declare a class name. When naming your classes you will use CamelCase formatting. CamelCase uses no spaces and capitalizes every word.

      # Class naming
      class MyFirstClass
      end
    
      class MySecondClass
      end
    

That about covers the most important style conventions to get started. If you'd like some more information about Ruby styling, check out the Ruby style guide.

Reading Documentation

As you begin your journey to becoming a programmer, one of the most important habits you'll need to develop is learning how to read documentation. Ruby, like all popular programming languages, comes with a rich set of standard libraries that you can use out of the box. However, you'll need to study the Ruby documentation - or Ruby docs - to gain familiarity with the different classes and methods available to you. Don't worry about the exact definition of classes or methods just yet, all that is coming up later in the book. These are terms best learned while working with Ruby. Be aware that some developers also refer to documentation as API. API is an acronym for application programming interface, and is a somewhat overloaded term that can refer to both how applications talk to each other, as well as documentation. Just remember, if someone says "Did you take a look at the Array API?", they're talking about the Ruby docs documentation for the Array class. But if someone says "What's the Twitter API?", they're talking about the programmatic interface to Twitter's services.

In this section we're interested in understanding how to read Ruby documentation, so let's take a look at an example. The below is a screenshot for the String class from the official Ruby documentation source, www.ruby-doc.org

Ruby Documentation Example

There's a lot to look at, so we've circled the three main areas to pay attention to.

Class name or Module name

In the first circle at the top, we see the word "String". This is the Class or Module (again, don't worry about what that is just yet, we will eventually cover it). In some documentation, you'll see the class name being referred to with a :: symbol, like this: Encoding::Converter. Here, the :: symbol is used to define a namespace, which is just a way to group classes in Ruby and differentiate from other classes with the same name. For example ActiveRecord::Base is referring to the Base class in the ActiveRecord module, to differentiate from other classes also named Base. However, when looking at the method list on the side bar, the :: means something different: it means that the method after the :: is a class method - we'll talk about this more later. For now, just realize that whether the top heading says String or Encoding::Converter, it's referring to the class or module name and the rest of the page will be documenting that class or module.

Methods

As a documentation convention, methods are listed out with either a :: or a # to indicate two different kinds of publicly accessible methods. Methods denoted by :: are considered class methods, while methods denoted by # are considered instance methods.

Beyond documentation, don't get caught up with these symbols because they have completely different meanings when executed in Ruby code. For example, the :: symbol is used as a namespace in actual Ruby code, while the # is used as a comment. Their use here in Ruby documentation is completely different from their use in actual code.

The meat of the ruby documentation for the String class describes String's Public Class Methods and Public Instance Methods. Clicking these methods will link to its section on the page showing its parameters, return values, and some example code that you can copy and paste to run in irb or Ruby file.

Example: Instance Methods vs Class Methods

The big take away from this documentation is that the Public Instance Methods can be applied to any instance of the class (we'll talk about "instances" and "objects" in the OOP section of the book, for now just follow the examples). We can look at the string "world wide web" and directly apply instance methods to it. For example, from the method list sidebar, we see that there's a #split method for strings, which means that split is an instance method, and we can call that method on any string directly:

irb :001 > "world wide web".split
 => ["world", "wide", "web"]

Further, we can see from the methods sidebar that there are two class methods: ::new and ::try_convert. Public Class Methods are called directly from the class.

irb :001 > b = String.new("blue")
 => "blue"
irb :002 > String.try_convert("red")
 => "red"

For now, these are the three most important things to remember when reading Ruby documentation: the class or module you're looking at, its available class methods, and its available instance methods - and how to use those methods. Knowing how to read a class's methods will help you play around with Ruby code and develop fluency.

Let's now cover the rest of the sections on the documentation page.

Parent

In Ruby every class sub-classes from some "parent". In order to really understand the previous sentence, you need to know object oriented programming, but we don't want to talk about that yet. The thing to understand is that the class you're looking at also has access to methods - both instance and class - documented in the parent class.

So in this example, the String class's parent is Object.

This means that in addition to the methods described in this doc, the methods of Object are also available to strings. This section of the page will link to the parent's documentation and is a good followup read if you aren't familiar with the parent object or you aren't finding methods you'd expect to see.

Class/Module Index

All classes are part of a namespace in Ruby and this menu is a list of all the other classes and modules that are part of the same namespace as the current class. If you look in the list you can see the same String class that will link to the document. You might see some items in this list that also use the :: symbol. In this case, it's using :: to indicate a namespace, like Math::DomainError.

Included Modules

Included modules indicate additional modules whose functionality is available to the String class. In the String example, the Comparable module is included. This means we can do something like this:

irb 001 > "cat".between?("ant", "zebra")
 => true

The between? method is not listed on the doc for the String class. However, if we look under the linked Comparable module, we find the between? method listed.

Summary

In this section we looked at Ruby's documentation. When in doubt, review the Ruby docs at www.ruby-doc.org that match the version of Ruby you are working with, and learn to get familiar with reading Ruby documentation. It should become a normal part of your workflow.

Using the Command Line and irb

This chapter will only give you a basic list of commands that you will use to run and test Ruby code. It is by no means an exhaustive list and is only the minimal amount needed.

This chapter will also cover how to use Ruby's interactive coding environment - irb. This is where you can test Ruby code snippets in the terminal.

A note to Windows users: the command line commands we show below may not work in Windows' default command prompt. Most Windows developers will use a terminal emulator, or an alternative, like Powershell. We recommend that all Windows developers get familiar with a terminal emulator or with Powershell and issue the commands below there.

Command Line

This book assumes that you know how to find the command line on your computer and type in commands. When you see the $ symbol, that represents the command line prompt. We'll also refer to the command line as the terminal. The prompt may look different on your computer, which is fine. The prompt varies depending on the machine you are working on.

To create a directory (or folder) called 'new_dir' type the following command:

$ mkdir new_dir

To navigate into the folder you just created:

$ cd new_dir

To create a file called 'new_file':

$ touch new_file.rb

To delete the file you just created:

$ rm new_file.rb

To navigate out of the current folder to the one above:

$ cd ..

To delete the directory you just created:

$ rmdir new_dir

Now, create the directory and file like you did above, again.

To remove the directory and file at the same time, navigate to the directory above 'new_dir' and type the following command:

$ rm -R new_dir

Be very careful with the rm command. It's very destructive and there's no way to recover from it. Use with caution. If in doubt, use your file navigation program (e.g. Explorer or Finder) and delete files and folders that way.

These are all of the commands that we are going to cover in the book. We do assume that you know your way around the command line, can navigate to different files, and can use basic commands. If you want to gain more comfort at the command line, there are many online tutorials and books that go into far more depth. Our book, Introduction to the Command Line, is one such option we recommend for learning more about the command line.

irb

Ruby has a built in interactive environment called "irb" that can be very helpful when writing Ruby code. At the command line type:

$ irb

This will produce a prompt that looks something like this:

2.0.0p-247 :001 >

The 2.0.0p-247 is telling us what version of Ruby we are running and the :001 tells us what line we are on. However, throughout this book, we will refer to the irb prompt like this:

irb :001 >

You can type in a Ruby command after the prompt and see its output and what it returns. For example, if you type the following command and press return to run it:

irb :001 > puts 'hello world!'

The output will look something like this:

irb :001 > puts 'hello world!'
hello world!
 => nil
irb :002 >

The line puts 'hello world!' prints the phrase 'hello world!' to the screen and returns a nil object value. We'll talk about method returns later. All you need to know now is that you can test code in Ruby's interactive environment, irb, when you have some doubts about a specific piece of code. It's also a great place to practice!

When you want to exit irb back to the command line, just type exit. Note that if you type exit from the command line, this will exit the shell, which means you have to start up your command line application again.

Running Ruby Code

When you have created a Ruby file, denoted by the .rb extension, you can run the code in that file by typing the ruby command followed by the file name in the command line. The following line shows how to run the code from a file called example.rb.

$ ruby example.rb

Pretty simple, eh?

Assuming that the example.rb file contained only the line puts 'hello world!', the following would print after running the file.

$ ruby example.rb
hello world!
$

When you run a Ruby file from the command line, the code gets executed by what's called an interpreter. You don't need to know a whole lot about the interpreter except the fact that it takes Ruby code and turns it into code that your computer understands.

The last tip is how to stop a running program. Sometimes, you'll have a long running Ruby program, or an error in the logic that results an infinite loop. To exit out of the program execution loop, use control-c. This will send an abort signal to the running program.

Remember...

Make sure you understand the difference between these three things that we covered.

  1. Using commands to manage files and folders at the command line (or terminal).
  2. Running Ruby commands in irb.
  3. Running Ruby code from a .rb file at the command line.

What Are Ruby "Gems"?

Rubyists call it RubyGems (one word), or just "gems" for short. There are two main sides to this term. The first side refers to a collection of Ruby files, or Ruby library, that performs a certain task. The other side refers to the publishing system that is behind organizing, listing, and publishing those libraries, or gems.

The publishing system behind RubyGems is designed to let you download, publish and use useful ruby libraries on your system. That system is powered by the website rubygems.org. The libraries that the system publishes are called "gems".

RubyGems is integrated into Ruby 1.9 and newer by default to help Rubyists speed up development. The code in a gem is like pre-packaged bundles of code written by someone to solve a useful problem. This means you'll spend time on useful features instead of reinventing the wheel. Ruby gems have versions based on the Semantic Versioning standard. A gem is said to have been "cut" when a new version becomes available. All the public installable gems are hosted at http://rubygems.org, though their code is hosted on a code repository, such as a Github.com repository.

How do I use it?

The gem command allows you to use RubyGems. When combined with the install command, one can download and install gems with their dependencies and any relevant documentation. The complete command is like so:

gem install <gem name>

where <gem name> is the actual name of the gem you want to install.

Installing gems like this is fine for one-time usage but with time, you'll lose track of which gems belong to which project. As you learn more Ruby, you'll be introduced to the Gemfile which offers a simple solution for organizing gems and their dependencies in a central location.

You can checkout RubyGems site for other useful commands.

For now, just understand that throughout this book and your journey as a Ruby developer, you may be required to gem install <some_gem>. All it's doing is going out to rubygems.org and pulling down the appropriate gem for you to use on your local machine.

Debugging Ruby code with Pry

Pry is a nifty library that doubles as an alternative to irb with a host of awesome features. In this section, we'll focus on its code debugging capabilities. To use pry we'll first have to install it:

gem install pry

This gives you the pry command which when entered in your terminal will open a new session just like you would with irb.

Use pry for debugging

Next, when you want to use pry for debugging you'll have to require "pry" and insert a binding.pry in your file like so:

# preparation.rb
require "pry"

a = [1, 2, 3]
a << 4
binding.pry     # execution will pause here, allowing you to inspect all objects
puts a

What this means is that when your program gets to where binding.pry has been declared, it'll open a new pry session instead of moving on to the next line in the code. This gives you the opportunity to play around with your variables and objects to see why things are not working. This is an extremely powerful debugging technique since it lets you pause execution to inspect the state of all variables and objects at that line of code. After you're done looking at your variables, you can continue the program execution with Ctrl + D.

We've just scratched the surface of what you should know to debug simple Ruby code. We just want to introduce you to this debugging technique in Ruby because it's a better alternative to using puts for debugging and gives you a good idea of what's really happening within your code.

Exercises

  1. Create a directory named my_folder and then navigate inside that directory. Create two files named one.rb and two.rb in the my_folder directory. Write a ruby program that outputs the line this is file one when you run the one.rb file. Then write another program that outputs this is file two when you run the two.rb file. (Hint: one.rb should have this in it puts "this is file one")

    Solution

    $ mkdir my_folder
    $ cd my_folder
    my_folder $ touch one.rb
    my_folder $ touch two.rb
    my_folder $ ruby one.rb
    this is file one
    my_folder $ ruby two.rb
    this is file two
    

    Video Walkthrough

    Please register to play this video
  2. When you are finished with the above and both programs are working correctly, navigate to the directory above the my_folder directory and delete all of the content you generated with one command.

    Warning: The rm method is a DANGEROUS command. Once you run this command there is no undoing it. It is permanent. Make sure you are in the correct directory and you are referencing the correct target directory when you execute this command.

    Solution

    my_folder $ cd ../
    $ rm -R my_folder
    

    Note, make sure to take care with the rm command. It can be very destructive and irreversibly delete folders and files.

    Video Walkthrough

    Please register to play this video