descriptionData Types
In Ruby, like in many other programming languages, data types are essential building blocks for creating and manipulating information. Understanding data types is crucial for writing effective and efficient code. In this lesson, we'll cover the basic data types in Ruby and how to work with them.
Integers represent whole numbers, both positive and negative, without any decimal point.
x = 10
y = -7
x.class #=> Integer
Floats represent numbers with decimal points. In Ruby, floating-point numbers are represented using the Float class.
x = 10.21
y = -7.77
x.class #=> Float
Strings represent sequences of characters. In Ruby, strings are enclosed in single quotes (') or double quotes ("). We will talk about the differences between them in the next lessons.
# Using single quotes
hello = 'Hello World!'
# Using double quotes
text = "I'm a text!"
hello.class #=> String
Booleans represent logical values - true or false. In Ruby, boolean values are represented using the TrueClass and FalseClass classes.
is_valid = true
is_open = false
is_valid.class #=> TrueClass
is_open.class #=> FalseClass
Arrays are ordered collections of elements. In Ruby, arrays can contain elements of any data type, and they are represented using square brackets ([]).
numbers = [7, 5, -4, 4, 0]
fruits = ["apple", "banana", "orange"]
numbers.class #=> Array
Hashes, also known are collections of key-value pairs. In Ruby, hashes arerepresented using curly braces ().
user = { name: "John Doe", age: 25 }
user.class #=> Hash
Symbols are immutable, unique identifiers. They are often used as keys in hashes or for naming things in Ruby. Symbols are represented using a colon (:) followed by the symbol name.
:name
:name.class #=> Symbol
In Ruby, a "nil" value represents the absence of any value or an empty value. It's Ruby's way of saying "nothing" or "null". In other words, when a variable is assigned the value nil, it means it doesn't point to any object or data.
nothing = nil
nothing.class #=> NilClass
In the following lessons, you will learn more about each data type.