Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
The Ruby Workshop
The Ruby Workshop

The Ruby Workshop: Develop powerful applications by writing clean, expressive code with Ruby and Ruby on Rails

Arrow left icon
Profile Icon Akshat Paul Profile Icon Wallace Profile Icon Dániel Szabó Profile Icon Philips
Arrow right icon
€32.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.3 (3 Ratings)
Paperback Oct 2019 544 pages 1st Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Akshat Paul Profile Icon Wallace Profile Icon Dániel Szabó Profile Icon Philips
Arrow right icon
€32.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.3 (3 Ratings)
Paperback Oct 2019 544 pages 1st Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

The Ruby Workshop

1. Writing and Running Ruby Programs

Overview

By the end of this chapter, you will be able to use the Interactive Ruby Shell (IRB) to write Ruby programs; execute Ruby code with a Ruby interpreter using Ruby (.rb) files; implement variables, literals, and constants in Ruby programs; use standard data types, such as numbers, Booleans, and strings, in Ruby programs; execute basic arithmetic operations on integer and floating-point numbers, implement string concatenation and interpolation in Ruby programs.

This chapter introduces the basics of Ruby and serves as a firm foundation to build the complex code that you will encounter later in the book.

Introduction

Ruby is a dynamic, interpreted, object-oriented programming language developed by Yukihiro ("Matz") Matsumoto at some point in the mid-1990s, with its first stable release in 1995. According to the creator of Ruby, it is highly influenced by Perl, Smalltalk, Ada, and Lisp. The influence of these languages on Ruby allows it to embrace various programming paradigms, such as functional, object-oriented, and imperative, with dynamic typing (referred to as duck typing in popular culture) and automatic memory management.

Being an interpreted scripting language, Ruby has the ability to make system calls directly, and has a long list of useful string operations where variable declaration and variable type are not required. Ruby wholly embraces object-oriented programming because everything in Ruby is an object. Ruby has a long list of keywords that make many operations a piece of cake. This means you can do more with less code.

Whether you are a newbie to the world of programming, or an experienced developer in other languages who is tired of the compilation processes, extra declarations, and the keywords of other languages, Ruby will be a revelation from the point of view of your productivity.

With all these characteristics, Ruby gives developers an enriching experience, making programming productive and fun. In addition to Ruby being a fantastic programming language, the Ruby community is also very friendly and supportive.

Key Features of Ruby

A number of key features of the Ruby language make it really unique in terms of working with it. It has very neatly assimilated the best features of many programming languages. Here are a few features of Ruby that make it a delight to program with:

  • Object-oriented
  • Interpreted language
  • Duck typing and dynamic typing
  • Multi-paradigm language
  • Reflection
  • Metaprogramming
    Figure 1.1: Key features of Ruby

Figure 1.1: Key features of Ruby

Object-Oriented

Ruby is thoroughly object-oriented, and objects are the basic building block of a Ruby program. Every value in Ruby is an object, even data types such as strings, numbers, and Booleans: everything is an object. This means that every object is part of a class that gives access to a wide range of methods to do incredible things. Each class is also an object in Ruby. Here's an example:

class Fruit
 #code
end

The preceding code defines the Fruit class. The following code shows that two new objects, fruit1 and fruit2, are derived from the Fruit class:

fruit1 = Fruit.new
fruit2 = Fruit.new

Interpreted Language

Ruby is an interpreted language, meaning that it's ready to run the program as soon as you finish typing. Unlike programming languages such as C++, Java, and Objective-C, which require code to be compiled before running, this is not the case with Ruby. Look at this example:

print "Hello World"

This code will immediately print Hello World, as follows:

Hello World

Duck Typing and Dynamic Typing

Dynamic typing means a variable can refer to objects of various types when the program is executed. There is no type checking in Ruby. Duck typing is a principle that denotes that an object is based on the value assigned to it rather than the type of variable. The underlying rule here is: "If it walks like a duck and quacks like a duck, then it must be a duck." Here's an example:

x= [:a, :b, :c]
x.map(&:to_s) # => ['a', 'b', 'c']

The preceding example illustrates how the x variable responds to map and returns the expected object. This means that the x variable here is considered an array.

Multi-paradigm Language

While languages are focused on one type of programming paradigm, besides being object-oriented, Ruby also allows procedural and functional styles of programming. The procedural paradigm refers to an instance where procedure calls are interpreted as function calls. However, functions do not exist in Ruby, and, therefore, methods can be created outside classes. Look at this example:

self # => main
def method1
  "John is developing a program."
end
def method2
  "Jane is developing another program."
end
method1 # => "John is developing a program."
method2 # => "Jane is developing another program."

Here, method1 and method2 are defined outside the classes; however, they are still a part of the main object.

Additionally, Ruby also features the functional style of programming, meaning it largely revolves around functions. Consider the following example:

def ruby_method(obj)
  obj - 1
end
print ruby_method(5)
=> 4

Here, the ruby_method always stores the result of the object passed as an argument, subtracting 1.

Reflection

Reflection in Ruby makes it very easy to understand what's happening at runtime because you can get a lot of information, such as class methods, inheritance hierarchies, and all the living objects in your running program. Here's an example:

class Box
  def hello
    "hello"
  end
end
# without reflection
obj = Box.new
obj.hello
# with reflection
class_name = "Box"
method_name = :hello
obj = Object.const_get(class_name).new
obj.send method_name

This shows that we can inspect every element of the code.

Metaprogramming

Ruby supports metaprogramming, which is a technique that helps you to write code that creates code on its own. This means it is able to create methods and classes dynamically. With metaprogramming, you can write methods and classes at runtime, which helps us to maintain a Don't Repeat Yourself (DRY) and maintainable code base. Here's an example:

['one', 'two', 'three'].each do |num|
  define_method(num) do
    num.upcase
  end
end
one # => "ONE"
two # => "TWO"
three # => "THREE"

The preceding code shows that we can make changes to the core Array class at runtime and modify it as required.

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.

Standard Data Types

The three major data types used in Ruby are as follows:

  • Number
  • String
  • Boolean

We shall look at each of these data types in detail in this section.

Number

Numbers in Ruby are objects that derive from the Numeric class. Let's look at the class hierarchy for various number types:

Figure 1.10: Number class hierarchy

Figure 1.10: Number class hierarchy

Of all of these, two of the most commonly used number types are integer and float, and there are a number of methods associated with both integer and floating-point numbers. Let's take a look at them one by one.

In Ruby, integers are represented by two classes: Fixnum and Bignum:

Figure 1.11: Integer types

Figure 1.11: Integer types

Both of them are inherited by the Integer class. As the name suggests, the Bignum class represents big numbers, and Fixnum is used to represent small numbers. Ruby manages the conversion between the two automatically. For example, if the result of an operation of two Fixnum numbers is outside the Fixnum range, it's converted to Bignum. From Ruby 2.4 onward, Ruby has unified these classes and automatically uses the Fixnum class for small numbers and Bignum for large numbers.

Exercise 1.05: Performing Common Integer Operations

In this exercise, we will perform common mathematical operations such as addition (+), subtraction (-), multiplication (*), and division (/) in Ruby:

  1. Go to the Terminal.
  2. Type irb to enter the IRB.
  3. Type the following code:
    1 + 2

    The output should be as follows:

    Figure 1.12: Output for the addition operator

    Figure 1.12: Output for the addition operator

  4. Perform subtraction using the - operator:
    3 - 1

    The output should be as follows:

    Figure 1.13: Output for the subtraction operator

    Figure 1.13: Output for the subtraction operator

  5. Perform multiplication using the * operator:
    3 * 3

    The output should be as follows:

    Figure 1.14: Output for the multiplication operator

    Figure 1.14: Output for the multiplication operator

  6. Perform division using the / operator:
    10 / 2

    The output should be as follows:

Figure 1.15: Output for the division operator

Figure 1.15: Output for the division operator

You may ask yourself how is the principle of BODMAS (Bracket, Open, Division, Multiplication, Addition, and Subtraction) managed by Ruby automatically. Ruby follows an order of precedence for operators, which defines the order in which the operators will take priority in any equation. We will learn about precedence in Chapter 3, Program Workflow.

Note

You can also divide up long integers by separating them with an underscore. For example, 121_334 will be read in Ruby as 121334

Exercise 1.06: Using Common Integer Methods to Perform Complex Arithmetic

In this exercise, we will try some common integer methods to make complex operations trivial. We will perform operations to calculate the next and previous numbers and calculate the Least Common Multiple (LCM) and Greatest Common Denominator (GCD) using built-in methods.

LCM is a method that finds the smallest multiple common to any two or more numbers, whereas GCD finds the largest divisor common to two or more numbers.

The following steps should help you with the solution:

  1. Go to the Terminal.
  2. Type irb to enter the IRB.
  3. Type the following code. .next will provide the next number:
    2.next

    The output should be as follows:

    Figure 1.16: Output for the next number

    Figure 1.16: Output for the next number

  4. Next, we will calculate the previous number using .pred:
    2.pred

    The output should be as follows:

    Figure 1.17: Output for the previous number

    Figure 1.17: Output for the previous number

  5. Then we calculate the LCM of 2 and 3 using .lcm:
    2.lcm(3)

    The output should be as follows:

    Figure 1.18: Output for the LCM of 2 and 3

    Figure 1.18: Output for the LCM of 2 and 3

  6. We also calculate the GCD of 2 and 3 using .gcd:
    2.gcd(3)

    The output should be as follows:

Figure 1.19: Output for the GCD of 2 and 3

Figure 1.19: Output for the GCD of 2 and 3

Most of these methods are self-explanatory, but let's go through each of them:

  • .next provides the next integer value.
  • .pred provides the preceding integer value.
  • .lcm gives us the least common multiple of the integer to which the method is applied and the value passed.
  • .gcd provides the greatest common divisor of the integer to which the method is applied and the value passed.

There are a number of methods available for the integer class, which you can play around with. Simply check them by using .methods on the integer.

Go to the Terminal. Type irb to enter the IRB and type the following code:

2.methods

The output should be as follows:

Figure 1.20: Available methods in Ruby

Figure 1.20: Available methods in Ruby

Note

To know more about all the methods and operations they can perform, refer to the official documentation at https://packt.live/2nc962i.

Floating-Point Numbers

Next, let's look into floating-point numbers. Floats are essentially imprecise decimal numbers in Ruby; we use the Float class with 15 digits of precision.

There are two ways to write floating-point numbers:

  • 1.121 – with a decimal point
  • 1.0e3 – adding an exponent provided there is one number before and after the decimal point

Exercise 1.07: Performing Common Operations for Floating-Point Numbers

In this exercise, we will try some common floating-point methods to make complex operations easy. We will also learn how to calculate the previous and next decimal number, as well as how to round off a decimal number completely or up to a certain decimal point:

  1. Go to the Terminal.
  2. Type irb to enter the IRB.
  3. Type the following code. Firstly, we have assigned our floating-point value to a num variable and applied various methods to it:
    num = 2.339
    num.ceil
    num.floor

    .ceil returns the closest next integer, and .floor returns the closest previous integer.

  4. Then we have .next_float. This returns the next floating-point value, which is an increment in the last digit of the number to 15 decimal places. Similarly, .prev_float returns the previous floating point value to 15 decimal places:
    num.next_float
    num.prev_float
  5. Next, we have .round, which removes the values after the decimal. If the value after the decimal point is less than 5, you get the previous integer, and if it is over 5, you get the next integer. When we pass a number to .round(2), we get a floating-point value to two decimal places:
    num.round
    num.round(2)

    The output should be as follows:

Figure 1.21: Output for floating-point number operations

Figure 1.21: Output for floating-point number operations

There are a number of methods available for the Float class, which you can play around with. Simply check them against .methods on any integer:

  1. Go to the Terminal.
  2. Type irb to enter the IRB.
  3. Type the following Ruby code:
    2.15.methods

The output should be as follows:

Figure 1.22: Methods for the Float class

Figure 1.22: Methods for the Float class

Note

To find out more about all the methods and the operations they can perform, refer to the official documentation at https://packt.live/2o7rYzS.

String

Strings in Ruby are derived from the String class, and there are over 100 methods to manipulate and operate on strings. This is perhaps because, in programming, a lot revolves around strings, and Ruby reduces the headache by managing a lot out of the box.

By default, Ruby comes with UTF-8 encoding, but this can be changed by placing a special comment at the top of a file:

# encoding: us-ascii
puts "Hello".encoding
output:
ruby strings.rb
#<Encoding:US-ASCII>

Note

If you remove the comment, by default, it will be UTF-8.

There are various ways to write strings in Ruby. These are some of the most common ones:

  • We can simply place anything between single quotes ('') and it becomes a string:
    'Ruby Fundamentals'
     => "Ruby Fundamentals"
  • In order to keep the single quote with the letters, we can escape it using the backslash character (\):
    '\'Ruby Fundamentals\''
     => "'Ruby Fundamentals'"
  • We can also use %q, as shown in the following examples, and place the required string in a delimiter, which can be a bracket, curly brackets, or something else:
    %q('Ruby' Fundamentals)
     => "'Ruby' Fundamentals"
    %q['Ruby' Fundamentals]
     => "'Ruby' Fundamentals"
    %q{'Ruby' Fundamentals}
     => "'Ruby' Fundamentals"
    %q<'Ruby' Fundamentals>
     => "'Ruby' Fundamentals"
  • We can also use double quotes (""), which is the cleanest way to define a string.
    "'Ruby' Fundamentals"
     => "'Ruby' Fundamentals"

    The output of all the preceding code should be as follows:

Figure 1.23: Ways to write strings in Ruby

Figure 1.23: Ways to write strings in Ruby

Exercise 1.08: Using Common String Methods

In this exercise, we will perform a number of common operations on a string. We will first assign a string to a variable, then find its size and length, and then change the case of the String value. We will then capitalize the string. All this will be done using the String class' built-in methods. Lastly, we will discuss the bang (!) operator and see how adding it impacts the results:

  1. Go to the Terminal.
  2. Type irb to enter the IRB.
  3. Enter the following code to define the string:
    title = "ruby fundamentals"

    The output should be as follows:

    Figure 1.24: Output for string definition

    Figure 1.24: Output for string definition

    Here, we are using the ruby fundamentals value for the title variable on which all the following operations will be executed.

  4. Next, we check the number of characters in this string, including white spaces, using .size:
    title.size

    The output should be as follows:

    Figure 1.25: Character count of a string

    Figure 1.25: Character count of a string

  5. Then, we also check the number of characters in this string, including white spaces, using .length:
    title.length

    The output should be as follows:

    Figure 1.26: String length calculation

    Figure 1.26: String length calculation

    .length is the same as size, but it is more meaningful in certain situations. Mostly, it is a matter of preference. Some developers prefer using .size for large collections of data, such as arrays, and hashes, and .length for smaller collections of data, such as strings.

  6. Next, we change the case of the string characters to uppercase using .upcase:
    title.upcase

    The output should be as follows:

    Figure 1.27: Uppercase string characters

    Figure 1.27: Uppercase string characters

  7. Similarly, we can change the casing to lowercase using .downcase:
    title.downcase

    The output should be as follows:

    Figure 1.28: Lowercase string characters

    Figure 1.28: Lowercase string characters

  8. We can also capitalize the first character of the string using .capitalize:
    title.capitalize

    The output should be as follows:

    Figure 1.29: Capitalized string characters

    Figure 1.29: Capitalized string characters

    Note that even after the operations are applied on the string, the original string object remains the same:

    title

    The output should be as follows:

    Figure 1.30: Original string object

    Figure 1.30: Original string object

  9. Let's now try the bang method. Bang methods end with an exclamation mark (!), and we can use them to modify the original object with the result of the operation. Since the bang method can permanently modify the receiver (the original value), it should be used carefully:
    title.capitalize!
    title

    The output should be as follows:

Figure 1.31: Bang operation on a string

Figure 1.31: Bang operation on a string

There are other operations as well that we can perform on strings, a common one being concatenation.

Exercise 1.09: Performing String Concatenation

In this exercise, we will be concatenating two string values that are assigned to different variables. We will solve the same problem in three ways:

  • Using the + operator
  • Using the .concat method
  • Using the << operator

The following steps will help you to perform the exercise:

  1. Go to the Terminal.
  2. Type irb to enter the IRB.
  3. Enter the following code. We first define the strings as var1 and var2:
    var1 = "Ruby"
    var2 = "Fundamentals"
  4. Next, we concatenate the two strings using whitespace:
    title = var1 + ' ' + var2

    The output should be as follows:

    Figure 1.32: Output using whitespace

    Figure 1.32: Output using whitespace

    To add a space between var1 and var2 in the final result, you can do this by chain two + operators with a whitespace in-between.

  5. We can also do the same with the .concat method and modify the Ruby code:
    title = var1.concat(var2)

    The output should be as follows:

    Figure 1.33: Output using the .concat method

    Figure 1.33: Output using the .concat method

  6. We can also concatenate the strings using the << operator:
    title = ""
    var1 = "Ruby"
    title << var1
    title << " "
    var2 = "Fundamentals"
    title << var2

    The output should be as follows:

Figure 1.34: Concatenation using the << operator

Figure 1.34: Concatenation using the << operator

Another way of accomplishing string manipulation is by using a technique called string interpolation. This works much more elegantly than the previous methods and allows you to combine the elements of different types together in a string. With string interpolation, we can combine strings and embed Ruby expressions in a string.

Exercise 1.10: Performing String Interpolation

In this exercise, we will use the title variable that contains a value for Ruby Fundamentals and interpolate it in a sentence:

  1. Go to the Terminal.
  2. Type irb to enter the IRB.
  3. Define the string:
    title = "Ruby Fundamentals"
    puts "My Favorite Ruby book is #{title}"

    The output should be as follows:

    Figure 1.35: String interpolation

    Figure 1.35: String interpolation

  4. We can also perform operations with string interpolation, for example, addition within a string:
    puts "My Favorite Ruby book is #{title} and I am using it for last #{10+30} days"

    The output should be as follows:

Figure 1.36: Addition operation in string interpolation

Figure 1.36: Addition operation in string interpolation

This is how we carry out addition operations with string interpolation.

Exercise 1.11: Extracting and Searching a Substring from a String

To extract certain characters from a string, follow these steps:

  1. Go to the Terminal.
  2. Type irb to enter the IRB.
  3. Define the string and then extract the characters, starting from the eighth position in an index to the second position from it:
    quote = "Just Do IT"
    quote[8,2]

    The output should be as follows:

    Figure 1.37: Extracting characters from a string

    Figure 1.37: Extracting characters from a string

    Thus, we have extracted characters, starting from the eighth position in an index to the second position from it, and hence get the characters IT.

  4. Now, we will use string methods that can check whether a certain character, or group of characters, exists in a string object:
    quote = "Just Do IT"
    quote.include?("Just")
    quote.include?("just")

    The output should be as follows:

Figure 1.38: Searching a substring from a string

Figure 1.38: Searching a substring from a string

Here, the characters must be together and in exactly the same order.

Exercise 1.12: Replacing Part of a String with Another String

In this exercise, we will replace the word Java in the sentence "My favorite book is Java Fundamentals" with the word Ruby. To do so, follow these steps:

  1. Go to the Terminal.
  2. Type irb to enter the IRB.
  3. Store the sentence My favorite book is Java Fundamentals in title:
    title = "My favorite book is Java Fundamentals"
  4. Type the following code, which replaces the word Java with Ruby in title:
    title["Java"] = "Ruby"
  5. Print title to confirm the change:
    title

    The output should be as follows:

Figure 1.39: Replacing string characters

Figure 1.39: Replacing string characters

We have now easily updated the specific value of the string object in the title variable.

If the original title was My favorite Java book is Java Fundamentals, we have Java repeated twice. In this case, only the first instance of Java would be replaced. The output would be My Favorite Ruby book is Java Fundamentals. This is where the gsub method comes into play. It is used to globally substitute a character, or set of characters, with another.

Exercise 1.13: Replacing All the Values inside a String Using gsub

In this exercise, we will use the gsub method to replace all the instances of Java with Ruby in a sentence:

  1. Go to the Terminal.
  2. Type irb to enter the IRB.
  3. Define the string value and apply the gsub method as follows:
    title = "My Favorite Java book is Java Fundamentals"
    title.gsub("Java", "Ruby")

    The output should be as follows:

Figure 1.40: Using the gsub method to replace characters in a string

Figure 1.40: Using the gsub method to replace characters in a string

This way, we can easily replace the same values across the object using gsub. This is very handy when we have to replace one character that is repeated and acts as noise in data with something meaningful.

Exercise 1.14: Splitting a String and Joining a String

In Ruby, we can split a string, which gives the result in an array (we will learn about arrays in the next chapter). In this exercise, we are going to split a string of words into an array of words.

  1. Go to the Terminal.
  2. Type irb to enter the IRB.
  3. Define the string and use the .split method to divide the string into an array of words:
    title = "My Favorite book is Ruby Fundamentals"
    title.split

    The output should be as follows:

    Figure 1.41: Splitting a string

    Figure 1.41: Splitting a string

  4. Use the split method to separate values in a string:
    months = "Jan; Feb; Mar"
    months.split(';')

    The output should be as follows:

    Figure 1.42: Splitting a string using a unique character

    Figure 1.42: Splitting a string using a unique character

  5. Join the array values in a string:
    data = ["My", "Favorite", "book", "is", "Ruby", "Fundamentals"]
    data.join

    The output should be as follows:

Figure 1.43: Joining arrays to form a string

Figure 1.43: Joining arrays to form a string

Thus, we have successfully used data.join to bring together values in a string.

The string class has several methods. You can use the following code to check the methods available in the string class:

"abc".methods

It lists all the methods that are present in the string class:

Figure 1.44: String methods

Figure 1.44: String methods

Note

To find out more about all the methods and the operations they can perform, refer to the official documentation at https://packt.live/2pDVtK5.

Activity 1.01: Generating Email Addresses Using Ruby

Imagine you have to write a Ruby program for a company (with the rubyprograms.com domain), which will generate a roster of email IDs of the company's employees. For this, we just need to accept user input in the form of the first name and last name of each employee and place them in an email format, which means adding an @ symbol between the two.

Observe the following steps to complete the activity:

  1. Create variables to accept the first names and last names of the individuals.
  2. Use gets.chomp to accept string input from users.
  3. Combine the first name and last name with the domain name and print the result.

    The expected output is as follows:

Figure 1.45: Output for email address generation

Figure 1.45: Output for email address generation

Note

The solution for this activity can be found via this link.

Boolean

Unlike other languages, Ruby does not have a Boolean type, but it has true and false Boolean values, which are essentially instances of the TrueClass and the FalseClass, respectively. These are singleton instances, which means that you can't create other instances of these classes.

Let's test this with an example:

a = nil
 => nil
a.nil?
 => true

The output should be as follows:

Figure 1.46: True and false classes

Figure 1.46: True and false classes

You get Boolean values when you check whether the a variable is nil.

We will learn more about the Boolean data type in Chapter 3, Controlling Program Flow.

Activity 1.02: Calculating the Area and Perimeter of a Candy Manufacturing Plant

In this activity, we will be using radius as the input to calculate the area and perimeter of a candy manufacturing plant.

Follow these steps to complete the activity:

  1. Go to the Terminal and use irb to enter the IRB.
  2. Define the variables for radius, perimeter, and area.
  3. Calculate the value received from user input stored in the radius variable and print the results for area and perimeter.

    The expected output is as follows:

Figure 1.47: Output for area and perimeter

Figure 1.47: Output for area and perimeter

Note

The solution for this activity can be found via this link.

Summary

In this chapter, we learned about the fundamentals of Ruby and its key features. We started with the history of Ruby and the key programming paradigms the language supports that make it unique and powerful at the same time. We then learned about using Ruby code with the IRB and also learned how to write code in Ruby files and execute it. Next, we delved into the standard data types in Ruby, which are number, Boolean, and string. Here, we implemented various operations on variables along with commonly used string operations, such as string concatenation and interpolation.

In the next chapter, we will learn how to work with data structures such as arrays and hashes. We will explore the details of the various powerful methods associated with them, and we will also learn how to create our own Ruby methods and call them, which is the bedrock of day-to-day programming with Ruby.

Left arrow icon Right arrow icon

Key benefits

  • Learn the fundamentals of Ruby object-oriented programming (OOP)
  • Use the Ruby on Rails framework to build interactive web applications
  • Discover how to quickly build complex programs with fewer lines of code

Description

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.

Who is this book for?

The Ruby Workshop is designed for anyone who is new to Ruby and wants a practical introduction to the language. Whether you're completely new to programming, or have experience in another language and want to broaden your skillset, this book will quickly get you up and running.

What you will learn

  • Master the syntax and features of Ruby to build useful applications
  • Use common design patterns to simplify code and improve efficiency
  • Understand how to implement object-oriented programming with Ruby
  • Explore ways to fetch, process, and output data
  • Work with public APIs and create reusable RubyGems
  • Debug code to troubleshoot application behavior
  • Create interactive web applications with Ruby on Rails
Estimated delivery fee Deliver to Norway

Standard delivery 10 - 13 business days

€11.95

Premium delivery 3 - 6 business days

€16.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 31, 2019
Length: 544 pages
Edition : 1st
Language : English
ISBN-13 : 9781838642365
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Norway

Standard delivery 10 - 13 business days

€11.95

Premium delivery 3 - 6 business days

€16.95
(Includes tracking information)

Product Details

Publication date : Oct 31, 2019
Length: 544 pages
Edition : 1st
Language : English
ISBN-13 : 9781838642365
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 105.97
The Python Workshop
€47.99
The PHP Workshop
€24.99
The Ruby Workshop
€32.99
Total 105.97 Stars icon
Banner background image

Table of Contents

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

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.3
(3 Ratings)
5 star 33.3%
4 star 33.3%
3 star 0%
2 star 0%
1 star 33.3%
Dave Patrick Sep 11, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
One of the best books to start your programming career as it has lot of examples and learning with examples gives confidence. The writers have explained enough theory and in a simple manner. There are also activities that further helps in implementing the concept you have studied. Overall it's an amazing book for those starting with a programming career and as advised by my teachers Ruby is wonderful language to learn and understand programming. I highly recommend this book for new developers. My next ruby book would be well-grounded Rubyist same teachers have who recommended this books have suggested it as next step.
Amazon Verified review Amazon
Kodzo Oct 22, 2024
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Great content
Subscriber review Packt
Jerry P. Brook Jan 07, 2020
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
I was very disappointed with this book.What I expected from a workshop, was explanations with examples and exercises.That is, explanations of the various entities of the Ruby programming language, such as the many data types; numbers, strings, collections, et cetera. What they are, and why you would use them.With examples of how to use them, and maybe even how not to use them.Exercises allowing the reader to test out that knowledge, and to become comfortable with the ways in which each data type acts, and what you get in return. Hands on testing of various scenarios, some good and some not so good, in order to build the readers understanding.I would have really appreciated the gotchas, that is, the ways that some of these items don’t work, even though one might have expected something different. Ruby is supposed to be the language of “least surprise”, however, there still are some.I haven’t seen the gotchas pointed out in any other books, and so I wasn’t expecting them here either. It’s always easier to show all the things that do work, and conveniently avoid the things that don’t. But that just causes frustration for the new learner as they think that they are doing something incorrectly, when that isn’t the case.So, what do you get?Well, the book begins in the middle of the language, expecting the reader to have a full understanding of the core concepts. From their they only provide brief descriptions of the concepts that they cover, and they follow the age old “type this and get that”.It is training not teaching, just robotic-ally do this and you will see this in return. Why do we get that? Don’t ask. How is it working? Don’t ask. What if we typed something else? Don’t bother.This neither a new, or interactive, approach to learning.To which I say don’t bother wasting your money on this book.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela