Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The Ruby Workshop

You're reading from   The Ruby Workshop Develop powerful applications by writing clean, expressive code with Ruby and Ruby on Rails

Arrow left icon
Product type Paperback
Published in Oct 2019
Publisher Packt
ISBN-13 9781838642365
Length 544 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (4):
Arrow left icon
Dániel Szabó Dániel Szabó
Author Profile Icon Dániel Szabó
Dániel Szabó
Akshat Paul Akshat Paul
Author Profile Icon Akshat Paul
Akshat Paul
Peter Philips Peter Philips
Author Profile Icon Peter Philips
Peter Philips
Cheyne Wallace Cheyne Wallace
Author Profile Icon Cheyne Wallace
Cheyne Wallace
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Writing and Running Ruby Programs 2. Ruby Data Types and Operations FREE CHAPTER 3. Program Flow Ruby Methods 5. Object-Oriented programming with Ruby 6. Modules and Mixins 7. Introduction to Ruby Gems 8. Debugging with Ruby 9. Ruby Beyond the Basics l 10. Ruby Beyond the Basics ll 11. Introduction to Ruby on Rails l 12. Introduction to Ruby on Rails ll Appendix

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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime