Understanding Data Types in Ruby
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 π:
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:
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?
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.
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:
You can do math with integers, too. For example, you can calculate the sum of two numbers and print out the result:
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:
You’ll see the integer written without the underscores:
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.
A 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.
You will print out floats in Ruby similar to you print out integers:
You also can declare a variable and assign a float:
And, similar to with integers, you’ll be able to do scientific discipline with floats in Ruby, too:
If you add a float to an integer in Ruby, you will get a float:
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
- 500 > 100 true
- 1 > 5 false
- less than
- 200 < 400 true
- 4 < 2 false
- 5 = 5 true
- 500 = 500 false
Like with numbers, you’ll be able to store a real or false value in a variable:
You will then print the Boolean value with a call to the print() function:
Since five isn’t larger than eight you will see the subsequent result:
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.
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:
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.
As with other data types, you’ll be able to store strings in variables:
And print out the string by calling the variable:
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.
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:
An array of floats sounds like this:
Here’s a list of strings:
Like order data types, you’ll be able to assign an array to a variable:
If we print out the variable, the output appearance precisely just like the array that we created:
You access individual elements in associate array by using an index number, beginning at zero.
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:
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:
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.
Sometimes we’d like the simplest way to label things in a program. That is what symbols are for.
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:
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.
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:
You will assign hashes to variables similar to other data types:
To retrieve values from the user hash, you utilize the key for the value:
You will use symbols because the keys in your hash rather than strings:
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:
You can also use a slightly different syntax when defining the hash:
You’ve looked at several data types, so let’s look at how Ruby works with those types.
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.
The variable t within the following example are often set to data type available:
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:
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.
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:
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:
TypeError: String can't be coerced into Integer
As will this code:
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:
In addition, you can use the kind_of? method to verify a certain type of data, like this:
This is especially useful when you have a variable and you want to determine its type:
You can also use this to verify that data coming from an external source is correct:
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:
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.
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.