Ruby Basics: Variables, Types, and Operators

· 10 min read · beginner
variables types operators beginner

Every Ruby program works with data. Before you can build anything useful, you need to understand how to store, access, and transform information. This tutorial covers the foundation every Ruby developer needs: variables, data types, and operators.

Variables in Ruby

Variables are named containers that hold values. Ruby uses dynamic typing, meaning you don’t need to declare a variable’s type explicitly.

# Simple variable assignment
name = "Alice"
age = 25
price = 19.99

puts name  # Output: Alice
puts age   # Output: 25

Variable Naming Conventions

Ruby has specific conventions for naming variables:

# snake_case for variables (all lowercase, underscores between words)
user_name = "Bob"
total_price = 100.50
is_active = true

# Constants start with an uppercase letter
MAX_SIZE = 100
API_KEY = "secret123"

Variable Scope

Ruby variables have different scopes based on their naming:

# Local variables: lowercase or underscore
local_var = "I am local"

# Instance variables: start with @
@instance_var = "I belong to this object"

# Class variables: start with @@
@@class_var = "I am shared across the class"

# Global variables: start with $
$global_var = "I am available everywhere"

For beginner Ruby code, stick with local variables. You’ll learn about the others as you advance.

Ruby’s Data Types

Ruby has several built-in data types. Here’s what you need to know:

Numbers

Ruby handles integers and floating-point numbers:

# Integers (no limit in Ruby)
count = 42
negative = -10
large_number = 1_000_000  # Underscores improve readability

# Floating-point numbers
price = 19.99
pi = 3.14159

# Basic arithmetic
sum = 10 + 5      # => 15
difference = 10 - 5  # => 5
product = 10 * 5   # => 50
quotient = 10 / 5  # => 2
remainder = 10 % 3  # => 1 (modulo)
power = 2 ** 8     # => 256 (exponentiation)

Strings

Strings hold text. Ruby provides many powerful string methods:

# Creating strings
greeting = "Hello, World!"
single_quoted = 'Single quotes treat everything literally'

# String interpolation (double quotes only)
name = "Ruby"
message = "Welcome to #{name}!"
# => "Welcome to Ruby!"

# Common string methods
"hello".upcase     # => "HELLO"
"HELLO".downcase   # => "hello"
"hello".capitalize  # => "Hello"
"  spaced  ".strip  # => "spaced"

# String concatenation
first = "Hello"
second = "World"
combined = first + " " + second  # => "Hello World"
combined2 = "#{first} #{second}"  # => "Hello World"

Booleans

Boolean values represent true or false:

is_active = true
is_deleted = false

# Ruby treats nil and false as falsy, everything else is truthy
# This is important for conditionals

Symbols

Symbols are immutable strings often used as keys or identifiers:

# Symbols are denoted with a colon
status = :active
action = :read

# Symbols are ideal for hash keys
user = { name: "Alice", status: :active }
# Same as: user = { :name => "Alice", :status => :active }

Arrays

Arrays store ordered collections of items:

# Creating arrays
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, true]

# Accessing elements (zero-indexed)
fruits[0]    # => "apple"
fruits[-1]   # => "cherry" (last element)
fruits[1..2] # => ["banana", "cherry"]

# Common array methods
fruits.length    # => 3
fruits.push("date")  # Add to end
fruits.pop       # Remove from end
fruits.include?("apple")  # => true

Hashes

Hashes store key-value pairs:

# Creating hashes
person = { name: "Alice", age: 30, city: "London" }

# Alternative syntax
person2 = { :name => "Bob", :age => 25 }

# Accessing values
person[:name]   # => "Alice"
person[:age] = 31  # Update value

# Common hash methods
person.keys    # => [:name, :age, :city]
person.values  # => ["Alice", 30, "London"]
person.has_key?(:name)  # => true

Operators in Ruby

Operators let you perform operations on values:

Arithmetic Operators

a = 10
b = 3

a + b    # => 13 (addition)
a - b    # => 7  (subtraction)
a * b    # => 30 (multiplication)
a / b    # => 3  (integer division in Ruby 2.x)
a.to_f / b  # => 3.333... (float division)
a % b    # => 1  (modulo - remainder)
a ** b   # => 1000 (exponentiation)

Comparison Operators

x = 5
y = 10

x == y   # => false (equal)
x != y   # => true  (not equal)
x > y    # => false
x < y    # => true
x >= y   # => false
x <= y   # => true

Logical Operators

a = true
b = false

a && b   # => false (AND)
a || b   # => true  (OR)
!a       # => false (NOT)

# Ruby also has keywords
a and b  # => false
a or b   # => true
not a    # => false

Assignment Operators

x = 5
x += 3   # => 8  (same as x = x + 3)
x -= 2   # => 6  (same as x = x - 2)
x *= 2   # => 12 (same as x = x * 2)
x /= 3   # => 4  (same as x = x / 3)

The Spaceship Operator

Ruby has a unique comparison operator that returns -1, 0, or 1:

5 <=> 10   # => -1 (left is less than right)
10 <=> 10  # => 0  (equal)
10 <=> 5   # => 1  (left is greater than right)

# Useful for sorting
[3, 1, 2].sort { |a, b| b <=> a }  # => [3, 2, 1] (descending)

When to Use What

  • Local variables for temporary data in methods and scripts
  • Symbols for hash keys and identifiers that won’t change
  • Strings for user-facing text and data
  • Integers for counting and exact arithmetic
  • Floats for decimal calculations (money, measurements)
  • Arrays for ordered collections
  • Hashes for key-value data and lookups

Conclusion

Understanding variables, types, and operators is essential for writing any Ruby code. These building blocks let you store data, perform calculations, and make decisions in your programs.

In the next tutorial, we’ll explore control flow — how to make your programs decide between different paths using conditionals and loops.


Next Tutorial: Control Flow: if, unless, loops