Data Types in Ruby featured image

An Overview of Data Types in Ruby

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:

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:

Time to try out integers in Ruby. The first example is printing a simple integer on the screen:

Data Types in Ruby 1

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:

Data Types in Ruby 2

We can also do math with integers. The following example demonstrates a simple summation of two integer numbers:

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:

Data Types in Ruby 3

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:

The next example demonstrates declaring a float variable:

We can also perform various mathematical operations on the float values and variables. The following example demonstrates a simple summation of two float numbers:

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:

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:

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:

We can also store strings in variables. The following example also incorporates string concatenation:

Data Types in Ruby 4

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:

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:

Data Types in Ruby 5

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:

Data Types in Ruby 6

Data Types in Ruby 7

Now, we can work with individual elements of the arrays:

Data Types in Ruby 7

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:

Data Types in Ruby 8

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:

Data Types in Ruby 9

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:

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:

Data Types in Ruby hashing in ruby

To retrieve the values of a key-value pair, we have to use the key. The following example demonstrates this process:

Data Types in Ruby retrieve value using key

Ruby also allows defining a hash using slightly different syntaxes ( : instead of =>):

Data Types in Ruby retrieving value using key

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:

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:

dynamically typed variables

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:

get input and cast

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:

mixing two datatypes

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:

get classes name

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:

check datatype

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?:

check datatype

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:

Happy Computing!

About Hark Labs

Software Engineer and enthusiast about new technologies