Preparations

Installing Ruby

For the purposes of this book, you'll need to have Ruby and RubyGems installed on your machine. We recommend that you use Ruby version 3.0.x, 3.1.x, or 3.2.x. We recommend Ruby 3.2.0 as the best choice. You may experience some issues with other versions, so install 3.2.0 if you can. If you cannot, a more recent version will probably give you the least trouble.

If you are working on a Mac or Linux machine, you may 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 if your system comes with Ruby, you should install a separate version of Ruby. 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 allow 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.

If you are a Mac user, that leaves you with one choice: install with Homebrew. We recommend installing one of the Ruby 3.2 versions for best results in this book. Follow these steps:

  • Install homebrew by following this link
  • Then run brew install ruby@3.2
  • If you are using bash, update PATH (substituting your username for USERNAME) echo 'export PATH="/opt/homebrew/opt/ruby@3.2/bin:$PATH"' >> /Users/USERNAME/.bash_profile
  • If you are using zsh, update PATH (substituting your username for USERNAME) echo 'export PATH="/opt/homebrew/opt/ruby@3.2/bin:$PATH"' >> /Users/USERNAME/.zshrc

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

Before you move on, use the ruby -v command in your terminal to determine that you're using the expected version of Ruby. Next, use which ruby to make sure you are not using /usr/bin/ruby -- that is the system Ruby and usually not the one you want. You may have to restart your terminal, or update your PATH if you continue to have problems.

Using a Code Editor

Developers often use a code editor to write code. A code editor creates plain text documents with no styling or formatting. If you already have a favorite code editor (e.g., Visual Studio Code, Vim, Emacs, etc.), use it to work through this book.

If you do not have a preferred code editor, we strongly recommend using Visual Studio Code (also known as VSCode). It's free and built as an open-source project. It's highly polished and pleasant to look at and use. Most surprisingly, perhaps, is that it comes from Microsoft. Its popularity is skyrocketing in the developer community.

VSCode comes in Mac, Windows, and Linux versions.

Avoid using word processors or advanced text editors when writing code: their focus is writing, not coding, and they often inject invisible characters or whitespace into the document to help format and style it. While that can make your prose look great, it doesn't work well with code. Code written with a word processor may not run at all, even if you copy and paste the code into a code editor before saving it.

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_some_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 PascalCase formatting, based on the naming style used in the Pascal programming language (the word is capitalized to distinguish it from camelCase). PascalCase uses no spaces and capitalizes every word. When Pascal came out, what is now known as PascalCase had been previously known as CamelCase, or upper CamelCase, so be aware that you may see it called this in some materials.

      # 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 FaceBook API?", they're talking about the programmatic interface to FaceBook's services.

It's worth pointing out that the state of the Ruby documentation is wanting. The official documentation is simply not easy to use when you're starting out with Ruby. It's confusingly laid out, has no index to speak of, and important information is just plain missing. Nevertheless, that's the documentation we will reference throughout Launch School's materials. A little later in this chapter, we will mention some other sources that may prove useful as a supplemental resource.

In this section we're interested in understanding how to read Ruby documentation, so let's take a look at an example. The image below is a screenshot for the String class from the official Ruby documentation source for the String class (note that your screen may look a little different to the screenshot shown):

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 one of 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.

Public, as used above, simply refers to methods that you can call when working with strings. We'll talk about "private" and "protected" methods in a later course.

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

If you want to find a specific Ruby class or module, the quickest way to do so, assuming you know its approximate name, is to click on the Search box and begin entering its name. Once the class name appears, all you have to do is click on it.

If you're not sure of the name and just want to browse the list of classes and modules, click on "Home" in the upper left corner (just above the Search box). Then scroll down on the left side to find the "Class and Module Index":

Ruby Class/Module Index

This section contains the names of all the classes and modules installed with Ruby. The list is fairly long, but you can usually find what you're looking for. You can also browse the list if you just want to see what's available.

Included Modules

If you return to the String documentation, then scroll the navigation bar down a bit, you'll soon spot the "Included Modules" section:

Ruby 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 in the String class documentation. However, if we look under the linked Comparable module, we find the between? method listed.

Supplemental Resources

As mentioned earlier in this chapter, the state of the official Ruby documentation is wanting. We will suggest a few other resources in this section.

In some ways, this unofficial Ruby documentation site is an improvement over the official site, but mostly in terms of appearance: it's easier on the eyes. Its home page is easier to navigate, and its search function is very good. It has documentation going back all the way to Ruby 2.3. We think it's worth checking out.

Another useful site is RubyDoc.info/stdlib/core. Some of the content includes additional information and examples not present in the official documentation. That can be helpful when you're having trouble understanding the official documentation. The site is easy to navigate, and the appearance is a significant step up from the official site. Unfortunately, it may be slow to update. At this writing in late 2023, the latest documentation covers only up to Ruby 3.0.2 (the current Ruby version is 3.2.2).

Another unofficial Ruby documentation site is also an improvement over the official site. Again, however, the improvements are mostly visual: the font and colors are easier to read. Its home page is easier to navigate. It includes documentation in multiple languages as well as documentation going back all the way to Ruby 1.8.6. However, the site is ad supported and suffers from broken internal links.

Finally, you can always use your favorite search engine to find answers to your questions. Be careful, though: searches often turn up outdated or incorrect content, so focus on recent items and try to look at several pages for conflicting information. AI tools like ChatGPT may also be helpful, but be extra careful: AI tools may lie to you. Convincingly.

Summary

In this section we looked at Ruby's documentation. When in doubt, review the Ruby docs on the official site. If you need to select the documentation for a different Ruby version, start here.

We urge you 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

If you're using AWS Cloud9 and experience weird screen behavior with the irb command, try using irb --nomultiline instead. If that solves the problems, you can set this as a configuration option. Create (or edit, if it already exists) a ~/.irbrc file that contains the following command (put the command at the end if the file already has content):

IRB.conf[:USE_MULTILINE] = false

Save the file, then the next time you start irb, it should automatically disable multiline mode.

This will produce a prompt that looks something like this:

3.2.0p-247 :001 >

The 3.2.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 in 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 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 check out the 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.

About the Exercises

A question that comes up often with our exercises is "My answer is different from Launch School's, but it still works. What should I do?"

Even with simple problems, there are often several different ways to solve an exercise, and sometimes many different ways. At this stage in your journey, the important part is to understand what you’ve read and be able to use that knowledge to answer questions, even if your answer is a little different. Once you're satisfied with your answer, you want to check it against Launch School's answer. Your answer doesn't have to be the same as ours. In fact, having an alternative answer affords you the opportunity to learn from seeing a different approach. How is your solution different from Launch School's? Do you understand our solution too?

Of course, you should be sure to check that your answer satisfies the requirements of the exercise. Does the output match the expected output, exactly? Does it properly handle any edge cases that may be mentioned? Sometimes, an answer may seem like it's correct, but you may have missed one of the requirements.

As long as you understand both your solution and ours, feel free to move on to the next exercise. At this point, you’re building up an awareness of the language, methods, and all the different ways you can do things. Having a different answer is not bad or a sign that you need to go back.

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