-
Book Overview & Buying
-
Table Of Contents
The Ruby Workshop
By :
The three major data types used in Ruby are as follows:
We shall look at each of these data types in detail in this section.
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
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
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.
In this exercise, we will perform common mathematical operations such as addition (+), subtraction (-), multiplication (*), and division (/) in Ruby:
irb to enter the IRB.1 + 2
The output should be as follows:

Figure 1.12: Output for the addition operator
- operator:3 - 1
The output should be as follows:

Figure 1.13: Output for the subtraction operator
* operator:3 * 3
The output should be as follows:

Figure 1.14: Output for the multiplication operator
/ operator:10 / 2
The output should be as follows:
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
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:
irb to enter the IRB..next will provide the next number:2.next
The output should be as follows:

Figure 1.16: Output for the next number
.pred:2.pred
The output should be as follows:

Figure 1.17: Output for the previous number
.lcm:2.lcm(3)
The output should be as follows:

Figure 1.18: Output for the LCM of 2 and 3
.gcd:2.gcd(3)
The output should be as follows:
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
Note
To know more about all the methods and operations they can perform, refer to the official documentation at https://packt.live/2nc962i.
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:
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:
irb to enter the IRB.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.
.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
.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
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:
irb to enter the IRB.2.15.methods
The output should be as follows:
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.
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:
'') and it becomes a string:'Ruby Fundamentals' => "Ruby Fundamentals"
\):'\'Ruby Fundamentals\'' => "'Ruby Fundamentals'"
%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"""), 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
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:
irb to enter the IRB.title = "ruby fundamentals"
The output should be as follows:

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.
.size:title.size
The output should be as follows:

Figure 1.25: Character count of a string
.length:title.length
The output should be as follows:

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.
.upcase:title.upcase
The output should be as follows:

Figure 1.27: Uppercase string characters
.downcase:title.downcase
The output should be as follows:

Figure 1.28: Lowercase string characters
.capitalize:title.capitalize
The output should be as follows:

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
!), 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
There are other operations as well that we can perform on strings, a common one being 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:
+ operator.concat method<< operatorThe following steps will help you to perform the exercise:
irb to enter the IRB.var1 and var2:var1 = "Ruby" var2 = "Fundamentals"
title = var1 + ' ' + var2
The output should be as follows:

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.
.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
<< operator:title = "" var1 = "Ruby" title << var1 title << " " var2 = "Fundamentals" title << var2
The output should be as follows:
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.
In this exercise, we will use the title variable that contains a value for Ruby Fundamentals and interpolate it in a sentence:
irb to enter the IRB.title = "Ruby Fundamentals"
puts "My Favorite Ruby book is #{title}"The output should be as follows:

Figure 1.35: String interpolation
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
This is how we carry out addition operations with string interpolation.
To extract certain characters from a string, follow these steps:
irb to enter the IRB.quote = "Just Do IT" quote[8,2]
The output should be as follows:

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.
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
Here, the characters must be together and in exactly the same order.
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:
irb to enter the IRB.My favorite book is Java Fundamentals in title:title = "My favorite book is Java Fundamentals"
Java with Ruby in title: title["Java"] = "Ruby"
title to confirm the change:title
The output should be as follows:
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.
In this exercise, we will use the gsub method to replace all the instances of Java with Ruby in a sentence:
irb to enter the IRB.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
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.
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.
irb to enter the IRB..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
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
data = ["My", "Favorite", "book", "is", "Ruby", "Fundamentals"] data.join
The output should be as follows:
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
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.
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:
gets.chomp to accept string input from users.The expected output is as follows:
Figure 1.45: Output for email address generation
Note
The solution for this activity can be found via this link.
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
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.
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:
irb to enter the IRB.radius, perimeter, and area.area and perimeter.The expected output is as follows:
Figure 1.47: Output for area and perimeter
Note
The solution for this activity can be found via this link.
Change the font size
Change margin width
Change background colour