Book Image

The Ruby Workshop

By : Akshat Paul, Peter Philips, Dániel Szabó, Cheyne Wallace
Book Image

The Ruby Workshop

By: Akshat Paul, Peter Philips, Dániel Szabó, Cheyne Wallace

Overview of this book

The beauty of Ruby is its readability and expressiveness. Ruby hides away a lot of the complexity of programming, allowing you to work quickly and 'do more' with fewer lines of code. This makes it a great programming language for beginners, but learning any new skill can still be a daunting task. If you want to learn to code using Ruby, but don't know where to start, The Ruby Workshop will help you cut through the noise and make sense of this fun, flexible language. You'll start by writing and running simple code snippets and Ruby source code files. After learning about strings, numbers, and booleans, you'll see how to store collections of objects with arrays and hashes. You'll then learn how to control the flow of a Ruby program using boolean logic. The book then delves into OOP and explains inheritance, encapsulation, and polymorphism. Gradually, you'll build your knowledge of advanced concepts by learning how to interact with external APIs, before finally exploring the most popular Ruby framework ? Ruby on Rails ? and using it for web development. Throughout this book, you'll work on a series of realistic projects, including simple games, a voting application, and an online blog. By the end of this Ruby book, you'll have the knowledge, skills and confidence to creatively tackle your own ambitious projects with Ruby.
Table of Contents (14 chapters)

Interactive Ruby Shell (IRB)

The easiest way to start playing around with Ruby is by using IRB, where I stands for Interactive and RB stand for the .rb extension of the Ruby programming files. IRB is a command-line interpreter and is also known as a REPL tool in Ruby, which means Read, Eval, Print, and Loop, and was inspired by Smalltalk. IRB is very useful for quick experiments, exploring Ruby, and testing fragments of code quickly.

IRB comes out of the box with Ruby, and you can access it using the irb command from the Terminal:

  1. Go to the Terminal (or Command Prompt) and type the following command:
    $ irb 
    >_ 
  2. Once the shell is open, you can type commands and get instant results. Try a simple puts command in Ruby using IRB:
    puts "Hello World"

    The output should be as follows:

Figure 1.2: Output for "Hello World"

Figure 1.2: Output for "Hello World"

Note

puts or p is used to print any string or value of a variable that follows puts or p.

Let's do some addition with the Interactive Ruby Shell:

  1. Go to the IRB shell.
  2. Type the following command:
    17 + 13

    The output should be as follows:

Figure 1.3: Addition output on irb

Figure 1.3: Addition output on irb

Note

You can use IRB or any IDE to complete the exercises/activities in this book.

Exercise 1.01: Creating and Assigning Variables

In this exercise, we will create a variable, assign an operation to it, and print it. Let's assign the calculation in the previous example to a variable, such as the number of students, and print it in IRB:

  1. Go to the IRB shell or the IDE of your choice.
  2. Type the following code:
    number_of_students = 17 + 13

    You should get the sum of 17 and 13 in the output.

  3. Next, we print the value carried by the number_of_students variable:
    puts number_of_students

    The output should be as follows:

Figure 1.4: Output for assigning variables

Figure 1.4: Output for assigning variables

Note

The Ruby variable stores the value assigned to a variable in one IRB session, as seen here with number_of_students.

Before we start the next exercise, please note that data types in Ruby symbolize various types of data, such as strings, numbers, decimal numbers, and text. All of these data types are based on classes; for example, string is an object of the String class, since Ruby is an object-oriented language. We will discuss a variety of data types in Ruby later in this chapter.

Exercise 1.02: Assigning a Variable of One Data Type to a Different Type

In this exercise, we will assign a string value to a variable of the integer data type. It is not necessary that a variable, once assigned, stays the same type forever. Let's assign a variable that holds an integer and another variable that has a string value:

  1. Continue from the previous example (if you are starting here, please complete Exercise 1.01, Creating and Assigning Variables).
  2. Type the following code:
    number_of_students

    This should give you an output of 30 as this was the value assigned in the previous exercise.

    Next, we assign a different value to the number_of_students variable:

    number_of_students = "not enough for a session"
    => "not enough for a session"

    The output should be as follows:

Figure 1.5: The output for variables assigned to a different data type

Figure 1.5: The output for variables assigned to a different data type

We can simply change the data type of a variable with the inbuilt Ruby methods. For example, to convert an integer to a string, we can use .to_s, and we can convert a string to an integer with .to_i.

We will study Ruby methods in detail in the later sections of this chapter.

Exercise 1.03: Getting the Type of a Variable

In this exercise, we will get information about the data type of a variable. Continuing on from the previous exercise, we can get a lot of information about the variable. First, let's see from which class the variable is derived. This can be achieved using the dot (.) operator on the variable itself.

  1. Continue from the previous example (if you are starting here, please complete Exercises 1.01, Creating and Assigning Variables and 1.02, Assigning a Variable of One Data Type to a Different Type).
  2. Now, we will try to identify the data type of our number_of_students variable using .class:
    number_of_students.class

    The output should be as follows:

    Figure 1.6: Output of the data type of a variable

    Figure 1.6: Output of the data type of a variable

    .class tells us about the class that the variable belongs to.

  3. The same can be achieved using the :: operator:
    number_of_students::class

In Ruby, the . and :: operators almost work in the same way. There is no major difference between :: and . when calling static methods. However, you may use the :: operator to access constants and other name-spaced things, where using the dot (.) operator is not possible. Aesthetically, . operator is preferable to :: operator.

Getting the Details of the Public Methods of an Object

We will now see various public methods that are available for an object by default from Ruby. Everything in Ruby is an object; the class itself is an object of Class. We can then check what interfaces are available for an object. Let's now see what public methods are associated with this object:

number_of_students.public_methods

The output should be as follows:

Figure 1.7: Output for public methods

Figure 1.7: Output for public methods

You can use all of the preceding public methods on this object to execute various operations and manipulate the value set in the object. If you look closely, some of the methods are self-explanatory, such as upcase, and downcase (we will discuss individual data types and their class later in this chapter).

Running Ruby Code from Ruby Files

In the previous section, we used IRB to execute some code snippets from the Terminal. But that's not usually the case when you write Ruby code. Whether you use a framework or run a standalone Ruby code, you would keep your code inside a Ruby file, which, in layman's terms, is a file with the .rb extension.

Let's try creating a hello_world.rb file and place some Ruby code in it. You can use your choice of IDE or simply use the Terminal.

  1. Create a new file and add the following code to it:
    puts "***"
    puts  "*****"
    puts  "*******"
    puts  "Hello World"
    puts  "*******"
    puts  "*****"
    puts  "***"
  2. Save this file in the desired location with the .rb extension. For example, save it as hello_world.rb.
  3. To execute this code, fire up your Terminal.
  4. Run the following command from root where your Ruby file is saved:
    $ ruby hello_world.rb

    The output should be as follows:

Figure 1.8: Output of the hello world program

Figure 1.8: Output of the hello world program

So far, we have learned how to print any value from a variable. Now that we know how to write and execute a code from a Ruby file, let's up the ante a bit by getting user input.

Exercise 1.04: Getting User Input in a Ruby Program

In this exercise, we will get the user to input some numerical data and perform a simple addition. To do so, follow these steps:

  1. Open your choice of IDE or the Terminal application.
  2. Create a new file.
  3. Add the following code to it. We use puts to print a string. The gets function is used to allow the input data to be stored in the num variable:
    puts  "Please enter a number to added to 5"
    num = gets
    sum = 5 + num.to_i
    puts  "The result is"
    puts sum

    We have converted the num variable explicitly to an integer using the built-in to_i method.

  4. Save the file as sum.rb.
  5. Open the Terminal and execute the following code:
    $ ruby sum.rb

    The output should be as follows:

Figure 1.9: Output for user input in Ruby

Figure 1.9: Output for user input in Ruby

By using the gets method, we were able to capture input from the user. When you executed the Ruby file, the cursor stopped for the input. The same input, as captured by the gets method, was used and added to 5.

Alternatively, there is a method called gets.chomp that removes the trailing line character from a string. Typically, the gets method will input the entire string, including the line break character. gets.chomp will remove line break characters from strings.