# Understanding Data Types in Ruby

Understanding Data Types in Ruby

## Introduction:

When you write programs, you use data types to classify data. Data types tell the computer a way to handle the data in your program. They conjointly verify what you’ll be able to do with the data, together with that operations you’ll be able to perform.

One way to think about data types is to consider the different types of data that we tend to use within the world. As an example, we tend to use whole numbers (0, 1, 2, …), integers (…, -1, 0, 1, …), and irrational numbers (π).

Usually, in math, we will mix numbers from differing types, and find some reasonably a solution. As an example, we tend to might want to add 5 to π:

``5 + π``

We will either keep the equation as the answer to account for the irrational number, or we will round π to a quick number of decimal places, and so add the numbers together:

``5 + π = 5 + 3.14 = 8.14 ``

But if we tend to attempt to assess numbers with another data type, like words, things begin to create less sense. How would we tend to solve the subsequent equation?

``sky + 8``

This is not one thing we tend to now knowledge to resolve. The computer cannot either as a result of the data is of two differing types. “Sky” could be a word, and 8 could be a whole number.

When we tend to write programs, we’ve got to take care concerning however we tend to assign values and the way we tend to manipulate them through operations like addition, subtraction, multiplication, and others.

In this tutorial, you will learn about the most important data type native to Ruby: integers, floats, strings, symbols, arrays, and hashes.

This isn’t associate complete investigation of data types, however it’ll assist you become familiar with the choices you’ve got out there to you in your programs.

You’ll then explore dynamic writing. Ruby programs determine data types based on what the variables contain, thus understanding however dynamic writing works can assist you avoid tough things in your own programs. And since variables will contain any worth, you may learn to spot a variable’s data type.

Let’s begin by viewing a way to work with whole numbers in Ruby.

## Integers

Like in scientific discipline, integers in computer programming are whole numbers which will be positive, negative, or 0 (…, -1, 0, 1, …). An integer is additionally remarkably called int.

You will print out an integer like this:

``print -25``

### Output

``````-25
``````

You can do math with integers, too. For example, you can calculate the sum of two numbers and print out the result:

``````sum = 116 - 68
print sum``````

### Output

``48``

When we tend to write out larger numbers, we tend to use commas to create them easier to scan. As an example, we’d write 1,000,000 for “one million”. You cannot use commas in your code, however Ruby allows you to use the underscore (_) character to create massive numbers a lot of readable.

Try it out:

large_number.rb
``````large_number = 1_234_567
print large_number``````

You’ll see the integer written without the underscores:

### Output

``````1234567
``````

The underscores allow you to write a lot of legible code if you’ve got to represent massive numbers in your programs.

As you learn a lot of concerning the Ruby language, you’ll have more opportunities to figure with integers. Let’s investigate a way to work with real numbers.

## Floating-Point Numbers

floating-point number or a float represents a true number. Real numbers are often either a rational or an irrational number; numbers that contain a third half, such as 9.0 or -116.42. In alternative words, a float in a Ruby program could be a range that contains a decimal point.

READ  Convert Data Types in Ruby

You will print out floats in Ruby similar to you print out integers:

``print 17.3``

### Output

``17.3``

You also can declare a variable and assign a float:

``````my_float = 17.3
print my_float``````

### Output

``17.3``

And, similar to with integers, you’ll be able to do scientific discipline with floats in Ruby, too:

``````sum = 564.0 + 365.24
print sum``````

### Output

``929.24``

If you add a float to an integer in Ruby, you will get a float:

``````sum = 564 + 365.24
print sum``````

### Output

``929.24``

Ruby can contemplate any range written without decimals as an integer (as in 138) and any number written with decimals as a float (as in 138.0).

Next, let’s investigate Boolean in Ruby.

## Boolean Data Types

Boolean’s are used to represent the truth values that are associated with the logic branch of arithmetic, that informs algorithms in technology. In Ruby, we tend to represent this data type with one in all two values, either true or false.

Many operations in scientific discipline provide answers that assess to either true or false:

• greater than
1. 500 > 100 true
2. 1 > 5 false
• less than
1. 200 < 400 true
2. 4 < 2 false
• equal
1. 5 = 5 true
2. 500 = 500 false

Like with numbers, you’ll be able to store a real or false value in a variable:

``result = 5 > 8``

You will then print the Boolean value with a call to the print() function:

``print result``

Since five isn’t larger than eight you will see the subsequent result:

### Output

``````false
``````

As you write a lot of programs in Ruby, you’ll become a lot of acquainted with how Boolean’s work and the how different functions and operations evaluating to either true or false will modification the course of the program.

Next, let’s explore operating with text in our programs.

## Strings

A string could be a sequence of one or a lot of characters, like letters, numbers, and symbols. Strings primarily exist within either single quotes (‘) or quotation mark (“) in Ruby, thus to make a string, enclose a sequence of characters in quotes, like this:

``"This could be a string in quotation mark."``

The easy program “Hello, World!” demonstrates however a string are often utilized in computer programming, because the characters that form up the phrase Hello, World! are a string.

``print "Hello, World!"``

As with other data types, you’ll be able to store strings in variables:

``output = "Hello, World!"``

And print out the string by calling the variable:

``print output``

### Output

``Hello, World!``

Like numbers, there are several operations that we can perform on strings among our programs so as to govern them to achieve the results we are seeking. Strings are important for communicating information to the user, and for the user to communicate information back to the program.

Sometimes you need to work with lists of data. that is wherever arrays are available handy.

## Arrays

An array will hold multiple values among one variable. This implies that you just will contain a listing of values among associate array and iterate through them. Each item or value that’s within associate array is named an element.

Arrays are defined by specifying values between square brackets [ ], separated by commas.

An array of integers sounds like this:

``[-3, -2, -1, 0, 1, 2, 3]``

An array of floats sounds like this:

``[3.14, 9.23, 111.11, 312.12, 1.05]``

Here’s a list of strings:

``['shark', 'cuttlefish', 'squid', 'mantis shrimp']``

Like order data types, you’ll be able to assign an array to a variable:

``sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp']``

If we print out the variable, the output appearance precisely just like the array that we created:

``print sea_creatures``
``['shark', 'cuttlefish', 'squid', 'mantis shrimp']``

You access individual elements in associate array by using an index number, beginning at zero.

``````puts sea_creatures[0]  # shark
puts sea_creatures[2]  # squid``````

To print out the last value, you’ll be able to use the index -1. Ruby also provides the .first and .last strategies for grabbing the primary and last entry, respectively:

``````puts sea_creatures.first  # shark
puts sea_creatures.last   # mantis shrimp``````

Arrays in Ruby will have many various styles of data. you’ll be able to store strings, symbols, associated even alternative arrays in an array:

``````record = [
:en,
"Sammy",
42,
[
"coral",
"reef"
]
]``````

Arrays in Ruby square are mutable, which implies you’ll be able to add values, take away values, and even modify entries within the array.

READ  C Programming for Suffix Array Set 1 Introduction

Sometimes we’d like the simplest way to label things in a program. That is what symbols are for.

## Symbols

A symbol is a special data type that acts like a label or an identifier in a Ruby program. Symbols are immutable, which implies that they can’t be modified. A symbol sounds like a variable declaration without a value. Here’s an example of a symbol:

``:time_zone``

In Ruby, you usually use a symbol to identify something of importance, whereas you’d use a string for text you wish to work with or manipulate. Each string in a Ruby program is its own object, with its own distinctive location in memory, although the strings square are identical.

But if you reference a similar symbol multiple times, you are referencing a similar object everyplace in your program, which implies you are referencing a similar memory location.

You’ll see this idea in action as we look at hashes, that allow you to associate keys with values.

## Hashes

A hash could be a dictionary-like collection of keys and values. These key-value pairs give a helpful way to store and access data. Hashes are often used to hold data that are related, like the information about a user. You define a hash like this:

``{"first_name" => "Sammy", "last_name" => "Shark"}``

You will assign hashes to variables similar to other data types:

``user = {"first_name" => "Sammy", "last_name" => "Shark"}``

To retrieve values from the user hash, you utilize the key for the value:

``````print user["first_name"]  # "Sammy"
print user["last_name"]   # "Shark"``````

You will use symbols because the keys in your hash rather than strings:

``user = {:first_name => "Sammy", :last_name => "Shark"}``

Using symbols as hash keys is most popular whenever possible. Every instance of a symbol points to a similar object, whereas each instance of a string refers to a unique object. Using symbols as keys ends up in slightly higher performance and fewer memory usage.

When you utilize symbols as keys, you utilize symbols to retrieve the values:

``````print user[:first_name]  # "Sammy"
print user[:last_name]   # "Shark"``````

You can also use a slightly different syntax when defining the hash:

``user = {first_name: "Sammy", last_name: "Shark"}``

This syntax is similar to the syntax used in JavaScript and other languages. This syntax defines the keys as Symbols, so you would access the entries using :first_name and :last_name instead of the strings “first_name” and “last_name”.

You’ve looked at several data types, so let’s look at how Ruby works with those types.

## Dynamic Typing

In Ruby, you do not expressly declare a data type before you assign a value; assigning the value determines the data type. Ruby uses dynamic writing, which implies type checking is finished at run-time instead of compile time, as in languages that use static writing. Ruby determines the data type from the data stored in the variable. This is often the same as information varieties in Python.

READ  Use Array Methods in Ruby

The variable t within the following example are often set to data type available:

``````t = 42        # t is an Integer
t = "Sammy"   # t is a String
t = :sammy    # t is a Symbol
t = true      # t is a boolean (true)
t             # t is nil``````

With dynamically-typed languages, you can reuse an existing variable to hold different data types.

This is useful when converting data from one type to another. For example, you might have this code which asks the user for a numerical value:

``````print "Please enter the length of the room: "
length = gets.chop``````

The data you get from the keyboard is always a string, so in order to do mathematical operations, you have to convert the length variable’s data to a number. In statically-typed languages, where you have to declare the variable’s data type before you can assign it a value, you would need a new variable to hold the converted data. But in Ruby, because it’s dynamically typed, you can reuse the length variable if you’d like.

``````# Convert the amount to a Float.
length = length.to_f``````

The rich man technique converts the String to a Float. Ruby also provides the to_i technique to convert Strings to Integers, and most objects can be converted to Strings using the to_s method:

``````42.to_s                    # "42"
(42.5).to_s                # "42.5"
["Sammy", "Shark"].to_s    # "[\"Sammy\", \"Shark\"]"``````

Ruby is dynamically typed, but it doesn’t allow you to perform operations on different types of data without converting them to the same type. For example, this code will result in an error:

``print 5 + "5"``

### Output

``TypeError: String can't be coerced into Integer``

As will this code:

``print "5" + 5``

### Output

``TypeError: no implicit conversion of Integer into String``

If you want to add the numbers together to get 10, convert the String to an integer. If you want to concatenate them together to get “55”, convert the Integer to a String.

Dynamic typing offers flexibility, but one downside is that you can’t always be sure what kind of data you’re working with, since the variable can contain any available type. Ruby provides ways for you to identify the type of data.

## Identifying Data Types

In Ruby, almost everything is an object. Integer, Float, Array, Symbol, and Hash are all Ruby objects, and that they all have a method called class that may tell you what type they’re. Even the Boolean’s true and false , and also the value nil are objects. Try it out for yourself:

``````42.class                   # Integer
(42.2).class               # Float
["Sammy", "Shark"].class   # Array
true.class                 # TrueClass
nil.class                  # NilClass``````

In addition, you can use the kind_of? method to verify a certain type of data, like this:

``42.kind_of?(Integer)    # true``

This is especially useful when you have a variable and you want to determine its type:

``````# somewhere in the code...
sharks = ["Hammerhead", "Tiger", "Great White"]
...
# somewhere else...

sharks.kind_of?(Hash)   # false
sharks.kind_of?(Array)  # true``````

You can also use this to verify that data coming from an external source is correct:

``````if data.kind_of? String
data = data.to_f
end``````

Ruby also provides the is_a? method, which does the same thing as kind_of? but might be a little easier to read for some developers:

``````if data.is_a? String
data = data.to_f
end``````

Using class, kind_of?, and is_a? can help you ensure you’re working with the right kind of data. As you learn more about Ruby, you’ll discover other ways to handle data that don’t involve explicitly checking the data types.

## Conclusion:

You can use many various data types in your Ruby programs. You currently have an improved understanding of the major data types available in Ruby programs.