Ruby Variables

Store and manipulate data in Ruby

๐Ÿ“ฆ Ruby Variables

Variables are containers that store data values in your programs. Ruby makes working with variables simple and flexible. You don't need to declare variable typesโ€”Ruby figures it out automatically based on the value you assign.


# Creating variables
name = "Ruby"
age = 30
price = 19.99
is_active = true

puts "Language: #{name}, Age: #{age}"
                                    

Output:

Language: Ruby, Age: 30

Variable Types

๐Ÿ“

Local Variables

Start with lowercase or underscore

name = "Alice"
_count = 10
๐ŸŽฏ

Instance Variables

Start with @ symbol

@age = 25
@email = "[email protected]"
๐Ÿ›๏ธ

Class Variables

Start with @@ symbols

@@count = 0
@@total = 100
๐Ÿ”’

Constants

Start with uppercase letter

MAX_SIZE = 100
PI = 3.14159

๐Ÿ”น Creating Variables

In Ruby, you create variables by simply assigning a value using the equals sign. No type declaration is neededโ€”Ruby automatically determines the data type.

# String variables
first_name = "John"
last_name = "Doe"

# Number variables
age = 30
height = 5.9

# Boolean variables
is_student = true
has_license = false

# Display variables
puts "Name: #{first_name} #{last_name}"
puts "Age: #{age}, Height: #{height}"
puts "Student: #{is_student}"

Output:

Name: John Doe
Age: 30, Height: 5.9
Student: true

๐Ÿ”น Variable Naming Rules

Ruby has specific rules for naming variables. Following these conventions makes your code readable and prevents errors.

Naming Rules:

  • Start with: Lowercase letter or underscore
  • Can contain: Letters, numbers, underscores
  • Cannot contain: Spaces or special characters
  • Case sensitive: name and Name are different
  • Use snake_case: user_name, not userName

๐Ÿ”ธ Valid Variable Names

# Good variable names
user_name = "Alice"
age_2024 = 25
_private_var = "hidden"
total_count = 100

puts user_name
puts age_2024

Output:

Alice
25

๐Ÿ”ธ Invalid Variable Names

# These will cause errors
# 2name = "Bob"        # Can't start with number
# user-name = "Alice"  # Can't use hyphens
# user name = "John"   # Can't have spaces
# @user = "Tom"        # @ makes it instance variable

๐Ÿ”น Data Types

Ruby variables can hold different types of data. Ruby automatically determines the type based on the value you assign.

๐Ÿ”ธ Common Data Types

# Integer (whole numbers)
count = 42
negative = -10

# Float (decimal numbers)
price = 19.99
temperature = -5.5

# String (text)
message = "Hello, Ruby!"
name = 'Alice'

# Boolean (true/false)
is_valid = true
is_empty = false

# Nil (no value)
nothing = nil

# Check types
puts count.class      # Integer
puts price.class      # Float
puts message.class    # String
puts is_valid.class   # TrueClass

Output:

Integer
Float
String
TrueClass

๐Ÿ”น Multiple Assignment

Ruby allows you to assign values to multiple variables in a single line, making code more concise:

# Assign multiple variables at once
x, y, z = 10, 20, 30
puts "x: #{x}, y: #{y}, z: #{z}"

# Swap variables easily
a = 5
b = 10
a, b = b, a
puts "a: #{a}, b: #{b}"

# Same value to multiple variables
num1 = num2 = num3 = 100
puts "All equal: #{num1}, #{num2}, #{num3}"

Output:

x: 10, y: 20, z: 30
a: 10, b: 5
All equal: 100, 100, 100

๐Ÿ”น Variable Scope

Variable scope determines where a variable can be accessed in your code. Different variable types have different scopes.

๐Ÿ”ธ Local Variables

# Local variable - only in current scope
def greet
  message = "Hello!"  # Local to this method
  puts message
end

greet
# puts message  # Error: message not defined here

Output:

Hello!

๐Ÿ”ธ Instance Variables

# Instance variable - accessible in class
class Person
  def set_name(name)
    @name = name  # Instance variable
  end
  
  def greet
    puts "Hello, I'm #{@name}"
  end
end

person = Person.new
person.set_name("Alice")
person.greet

Output:

Hello, I'm Alice

๐Ÿ”น Constants

Constants are variables whose values shouldn't change. They start with an uppercase letter and are typically written in all caps:

# Define constants
MAX_USERS = 100
PI = 3.14159
APP_NAME = "MyApp"

puts "Maximum users: #{MAX_USERS}"
puts "Pi value: #{PI}"
puts "Application: #{APP_NAME}"

# Ruby warns if you try to change a constant
# MAX_USERS = 200  # Warning: already initialized constant

Output:

Maximum users: 100
Pi value: 3.14159
Application: MyApp

๐Ÿ”น Variable Operations

You can perform various operations on variables depending on their data type:

๐Ÿ”ธ Numeric Operations

# Math with variables
x = 10
y = 3

puts "Sum: #{x + y}"
puts "Difference: #{x - y}"
puts "Product: #{x * y}"
puts "Division: #{x / y}"
puts "Modulus: #{x % y}"

# Compound assignment
x += 5  # Same as x = x + 5
puts "After += 5: #{x}"

Output:

Sum: 13
Difference: 7
Product: 30
Division: 3
Modulus: 1
After += 5: 15

๐Ÿ”ธ String Operations

# String concatenation
first = "Hello"
last = "World"

full = first + " " + last
puts full

# String interpolation (preferred)
name = "Ruby"
greeting = "Welcome to #{name}!"
puts greeting

# String methods
text = "ruby programming"
puts text.upcase
puts text.capitalize
puts text.length

Output:

Hello World
Welcome to Ruby!
RUBY PROGRAMMING
Ruby programming
16

๐Ÿง  Test Your Knowledge

Which symbol starts an instance variable in Ruby?