Ruby is a well-known programming language. It aims to improve simplicity and productivity. It’s also a fully object-oriented programming language. In addition, Ruby comes with an elegant syntax that’s natural to read and easy to write.
Any programming requires managing various data types. A data type describes a specific class of data. It tells the machine how it should handle the data in the program. Data types are crucial for determining what can be done with the data (including the operations that can be performed). In this tutorial, we will dive deeper into the data types available in Ruby. We will also explore dynamic typing. Using this feature, Ruby can automatically determine the data type of a variable without explicitly declaring it. Let’s start!
Prerequisites
To practice and implement the steps demonstrated in this guide, you will need the following components:
- A properly-configured Linux system. Learn more about setting up a personal Ubuntu server on CloudSigma.
- A properly-configured Ruby development environment. Check out the official documentation of installing Ruby on Ubuntu (using APT).
Data types in Ruby
Ruby features all the common data types you will encounter in any programming language: integers, floats, strings, arrays, symbols, hashes, etc. Next, we will provide an overview of how to work with Ruby’s various data types.
Step 1 – Integers
Similar to math, integers in computer programming are whole numbers. The value can be positive, negative, or 0. The value range is as follows:
1 |
{-∞, …, -1, 0, 1, …, ∞} |
Time to try out integers in Ruby. The first example is printing a simple integer on the screen:
1 2 |
print 99 print "\n" |
Next, we will work with an integer variable. Here, the variable sample_int contains an integer value (99) and the print function prints the variable value on the screen:
1 2 3 |
sample_int = 99 print sample_int print "\n" |
We can also do math with integers. The following example demonstrates a simple summation of two integer numbers:
1 2 3 |
sample_int = 99 + 100 print sample_int print "\n" |
When we’re working with big numbers, we often use commas (,) to make it easier to read. For example, one million (1000000) is written as 1,000,000 for better readability. While using commas is prohibited, Ruby allows using underscores ( _) as the delimiter. Have a look at the following example:
1 2 3 |
sample_int = 1_000_999 print sample_int print "\n" |
Using underscores improves the readability of the code, especially when dealing with big integer values.
Step 2 – Floating-Point Numbers
A floating-point number (or float for short) represents a real number. Similar to the mathematical definition, real numbers can be rational or irrational. In Ruby, a float is basically a number containing a decimal point.
Let’s try printing a float value on the screen:
1 2 |
print 55.66 print "\n" |
The next example demonstrates declaring a float variable:
1 2 3 |
sample_float = 55.66 print sample_float print "\n" |
We can also perform various mathematical operations on the float values and variables. The following example demonstrates a simple summation of two float numbers:
1 2 3 |
sample_float = 55.66 + 99.222 print sample_float print "\n" |
What if we added a float and an integer? The resultant value will be float. In the following example, despite 55.0 being a full number, it’s treated as a float:
1 2 3 |
sample_float = 55.0 + 10 print sample_float print "\n" |
Step 3 – Boolean
Booleans represent the truth values of the logic branch of mathematics. In Ruby, Boolean data types are represented by two values: true and false:
-
Greater than
-
100 > 99: true
-
99 > 100: false
-
-
Less than
-
500 < 999: true
-
999 < 500: false
-
-
Equal
-
10 == 10: true
-
9 == 99: false
-
Similar to numbers, we can also store a true or false value in a variable. The following example demonstrates this feature:
1 2 3 |
result = 9 == 99 print result print "\n" |
Step 4 – Strings
In programming, a string is represented as a sequence of characters (alphabets, numbers, and symbols). In Ruby, strings exist within single quotes ( ') or double quotes ( "). We already covered using strings in Ruby in detail, so this will be a short section.
The following example is a basic hello world program in Ruby:
1 |
print "hello world!\n" |
We can also store strings in variables. The following example also incorporates string concatenation:
1 2 |
username = "Cloudsigma" print "hello, " + username + "!\n" |
Step 5 – Arrays
An array is a data structure that can store a fixed-size collection of elements of the same data type. It can also be conceptualized as a collection of variables of the same data type. It’s one of the most fundamental data structures in most modern programming languages.
In Ruby, an array is defined as follows:
1 |
[value_1, value_2, …, value_N] |
It’s possible to create an array of any other data types we’ve discussed so far (integer, float, and strings). Here are some examples:
-
Integer: [-5, 0, 5]
-
Float: [-9.99, -6.99, -3.99, 0, 3.99]
-
String: [“the”, “quick”, “brown”, “fox”]
The following example implements all these types of arrays:
1 2 3 4 5 6 |
print [-5, 0, 5] print "\n" print [-9.99, -6.99, -3.99, 0, 3.99] print "\n" print ["the", "quick", "brown", "fox"] print "\n" |
Note that when the print function encounters an array, it prints the entire array on the screen. For more convenience, you will often encounter arrays as variables. Let’s update the code:
1 2 3 4 5 6 7 8 9 10 |
array_int = [-5, 0, 5] print array_int print "\n" array_float = [-9.99, -6.99, -3.99, 0, 3.99] print array_float print "\n" array_string = ["the", "quick", "brown", "fox"] print array_string print "\n" |
Now, we can work with individual elements of the arrays:
1 2 3 4 5 6 7 8 9 |
array_int = [-5, 0, 5] print array_int[2] print "\n" array_float = [-9.99, -6.99, -3.99, 0, 3.99] print array_float[1] print "\n" array_string = ["the", "quick", "brown", "fox"] print array_string[3] print "\n" |
Note that in Ruby, the index value of arrays starts with 0.
For convenience, arrays in Ruby come with the .first and the .last methods that print the first and the last elements:
1 2 3 4 |
array_float = [-9.99, -6.99, -3.99, 0, 3.99] puts array_float.first puts array_float.last print "\n" |
In Ruby, arrays have another interesting feature. It can hold different types of data at the same time. For example, you can store strings, symbols, and even other arrays:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
mixed_array = [ "hello", 99.99, "world", [ "the", "quick", "brown", "fox" ] ] print mixed_array print "\n" print mixed_array[3] print "\n" |
Step 6 – Symbols
In Ruby, a symbol is a special data type that acts like a label or an identifier. Symbols are immutable, meaning they can’t be changed. Symbols appear as if declaring variables without any value.
Here’s an example of a symbol:
1 |
:time_zone |
Generally, symbols are used to identify something important. For other situations, however, strings are more than sufficient.
Ruby, being an object-oriented language, treats everything as an object (including strings) with its unique memory location, even if the strings are identical. However, when you’re referencing a symbol, it’s the same object everywhere in the program, the same memory location.
Step 7 – Hashes
A hash is a dictionary-like collection of keys and values. Oftentimes, hashes are used for storing related data, for example, information about a user.
Here’s a quick example of a hash. We’ve created a hash user_info containing the username and password of a user:
1 2 3 4 5 6 |
user_info = { "username" => "HelloWorld999", "password" => "password123" } print user_info print "\n" |
To retrieve the values of a key-value pair, we have to use the key. The following example demonstrates this process:
1 2 3 4 5 6 7 |
user_info = { "username" => "HelloWorld999", "password" => "password123" } print user_info["username"] print "\n" |
Ruby also allows defining a hash using slightly different syntaxes ( : instead of =>):
1 2 3 4 5 6 |
user_info = { username: "HelloWorld999", password: "password123" } print user_info[:password] print "\n" |
This syntax structure is similar to the syntax used in other languages, for example, JavaScript. In this syntax structure, the keys are defined as symbols. That’s why instead of using "username", we’re using: username to access the value.
Dynamic Typing
You may have noticed already that when declaring a variable, we don’t have to explicitly assign a data type. Instead, the value of the variable determines the data type. Ruby uses dynamic typing where type checking is performed at runtime. In contrast, the data types are determined during compilation in static typing programming languages (C/C++, for example).
In the following example, all the values assigned at the variable dyn_var are valid:
1 2 3 4 5 |
dyn_var = 123 dyn_var = 456.789 dyn_var = true dyn_var = "the quick brown fox" dyn_var |
In dynamically-typed languages, we are free to reuse an existing variable to store different data types. Here, the previous example is updated to demonstrate this phenomenon:
1 2 3 4 5 6 7 |
dyn_var = 123 puts dyn_var dyn_var = 456.789 dyn_var = true dyn_var = "the quick brown fox" puts dyn_var dyn_var |
As this example demonstrates, every time a new value is assigned, it changes the data type of dyn_var on the go. It’s useful when converting one data type to another. The following example demonstrates this:
1 2 3 4 |
print "enter length: " length = gets.chop length = length.to_f puts length |
Here,
-
Because keyboard inputs are strings, length is a string at first.
-
As our desired value is a float, we’re converting the string value to float using the to_f method.
-
Because of the change of value, length is assigned the float data type. This is what we see when printing its value on the screen.
What would happen if we tried mixing two different data types together? Ruby will throw an error. Take a look:
1 |
print 9 + "77" |
Data Type Identification
In Ruby, everything is treated as an object. Every object in Ruby comes with the method class. When called, this method tells what data type the source is. Here are some examples of using the class method:
1 2 3 4 |
puts 55.class puts (55.55).class puts true.class puts nil.class |
Another way to tell the data type is using the kind_of? method. It checks the data type of the object against the data type asked and returns a Boolean value. Check it out in the following example:
1 2 |
puts 55.kind_of?(Float) puts 55.kind_of?(Integer) |
Similarly, there’s another method is_a? that compares the data type and returns a Boolean value. The only difference is the label of the method. However, it may be preferable because it’s a little easier for developers to read and make sense of. Update the previous example with is_a?:
1 2 |
puts 55.is_a?(Float) puts 55.is_a?(Integer) |
Final Thoughts
Working with any programming language requires a good understanding of the data types it supports. In this guide, we explored the most common data types used in Ruby programming. We discussed and demonstrated integers, floats, strings, symbols, Booleans, and hashes (with examples).
Take a look at more tutorials from our blog that will help you explore Ruby:
- Installing Ruby on Rails with RVM on Ubuntu 20.04
- Setting up Ruby on Rails with PostgreSQL
- Using MySQL with Ruby on Rails App on Ubuntu 21.04
- Exploring CloudSigma PaaS: How to Utilize Ruby PaaS Hosting Services?
Happy Computing!
- How To Enable, Create and Use the .htaccess File: A Tutorial - March 8, 2023
- An Overview of Queries in MySQL - October 28, 2022
- Introduction to Cookies: Understanding and Working with JavaScript Cookies - October 25, 2022
- An Overview of Data Types in Ruby - October 24, 2022
- The Architecture of Iptables and Netfilter - October 10, 2022