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.
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
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.
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:
- Go to the Terminal.
- Type
irb
to enter the IRB.
- Type the following code:
1 + 2
The output should be as follows:
Figure 1.12: Output for the addition operator
- Perform subtraction using the
-
operator:3 - 1
The output should be as follows:
Figure 1.13: Output for the subtraction operator
- Perform multiplication using the
*
operator:3 * 3
The output should be as follows:
Figure 1.14: Output for the multiplication operator
- Perform division using the
/
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
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:
- Go to the Terminal.
- Type
irb
to enter the IRB.
- 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
- 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
- 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
- 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
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.
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:
- Go to the Terminal.
- Type
irb
to enter the IRB.
- 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.
- 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
- 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
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:
- Go to the Terminal.
- Type
irb
to enter the IRB.
- Type the following Ruby code:
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.
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
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:
- Go to the Terminal.
- Type
irb
to enter the IRB.
- Enter the following code to define the string:
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.
- 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
- 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
.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.
- 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
- Similarly, we can change the casing to lowercase using
.downcase
:title.downcase
The output should be as follows:
Figure 1.28: Lowercase string characters
- 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
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
- 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
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:
- Go to the Terminal.
- Type
irb
to enter the IRB.
- Enter the following code. We first define the strings as
var1
and var2
:var1 = "Ruby"
var2 = "Fundamentals"
- Next, we concatenate the two strings using whitespace:
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.
- 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
- 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
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:
- Go to the Terminal.
- Type
irb
to enter the IRB.
- Define the string:
title = "Ruby Fundamentals"
puts "My Favorite Ruby book is #{title}"
The output should be as follows:
Figure 1.35: String interpolation
- 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
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:
- Go to the Terminal.
- Type
irb
to enter the IRB.
- 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
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
.
- 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
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:
- Go to the Terminal.
- Type
irb
to enter the IRB.
- Store the sentence
My favorite book is Java Fundamentals
in title
:title = "My favorite book is Java Fundamentals"
- Type the following code, which replaces the word
Java
with Ruby
in title
: title["Java"] = "Ruby"
- Print
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.
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:
- Go to the Terminal.
- Type
irb
to enter the IRB.
- 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
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.
- Go to the Terminal.
- Type
irb
to enter the IRB.
- 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
- 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
- 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
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.
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:
- Create variables to accept the first names and last names of the individuals.
- Use
gets.chomp
to accept string input from users.
- 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
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
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:
- Go to the Terminal and use
irb
to enter the IRB.
- Define the variables for
radius
, perimeter
, and area
.
- 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
Note
The solution for this activity can be found via this link.