ruby
  1. ruby-data-types

Ruby Data Types

Data types define the type of data that a variable can store in Ruby. Ruby is a dynamically-typed language, which means that the data type is inferred by the interpreter at run time.

Data Types in Ruby

Integer

Integers are whole numbers without decimal points. In Ruby, integers can be positive, negative, or zero.

# Example
x = 10
y = -5

Float

Floats are numbers with decimal points. In Ruby, floats can be positive, negative, or zero.

# Example
x = 10.5
y = -3.2

Boolean

Boolean values are either true or false. In Ruby, the boolean values are represented by true and false.

# Example
is_ruby_fun = true
is_python_better = false

String

Strings are a sequence of characters enclosed in single or double quotes.

# Example
name = "John"
message = 'Hello World!'

Array

An array is an ordered list of elements enclosed in square brackets. Each element in the array can be of any data type.

# Example
numbers = [1, 2, 3, 4, 5]
names = ['John', 'Jane', 'Mike']

Hash

A hash is a collection of key-value pairs enclosed in curly braces. Each key in the hash must be unique.

# Example
person = { name: 'John', age: 30, city: 'New York' }

Type Conversion

Ruby provides methods to convert one data type to another. Here are some examples of type conversion in Ruby:

# Integer to Float
x = 10
y = x.to_f
# y is now 10.0

# Float to Integer
x = 10.5
y = x.to_i
# y is now 10

# String to Integer
x = "10"
y = x.to_i
# y is now 10

# String to Float
x = "10.5"
y = x.to_f
# y is now 10.5

Importance of Data Types

Data types provide structure and meaning to the data in a program. By defining the data type, you can ensure that the variable contains the right kind of data, and you can perform operations on it accordingly.

For example, performing mathematical operations on a string will result in an error because a string is not a numeric data type.

Summary

Ruby has several built-in data types, including integers, floats, booleans, strings, arrays, and hashes. These data types provide structure and meaning to the data in a program. Data type conversion ensures that the program can perform the right operations on the data. It's essential to understand the data types in Ruby to write clear and concise code.

Published on: