467
Variables in Ruby are containers for storing data.
They allow you to label and reference information throughout your code.
Ruby is a dynamically-typed language, so you don’t need to declare the type of a variable explicitly—it’s determined at runtime.
What You’ll Learn
1. What Are Variables?
A variable in Ruby stores a value that can be reused or manipulated. You assign a value to a variable using the = operator:
name = "Ruby" puts name # Output: Ruby
2. Declaring and Assigning Variables
Example: Assigning Values to Variables
name = "Alice" age = 30 is_student = true puts name # Output: Alice puts age # Output: 30 puts is_student # Output: true
Reassigning Variables
x = 10 x = "Hello" puts x # Output: Hello
3. Variable Naming Rules
- Must start with a lowercase letter or an underscore (_).
- Can include numbers, but cannot start with them.
- Cannot use special characters like @, $, %, etc., except for special variable types.
- Reserved keywords (e.g., class, if, end) cannot be used as variable names.
Valid Examples
name = "John" _age = 25 score2 = 99
Invalid Examples
# 2score = 50 # Invalid: Starts with a number # if = "test" # Invalid: Uses a reserved keyword
4. Types of Variables
Ruby supports four types of variables:
4.1 Local Variables
- Starts with a lowercase letter or _.
- Scope is limited to the block or method where it’s defined.
def example local_var = "I'm local" puts local_var end example # Output: I'm local # puts local_var # Error: undefined local variable
4.2 Instance Variables
- Starts with @.
- Belongs to an object and is available across methods in the same object.
- Default value is nil.
class Person def initialize(name) @name = name end def greet puts "Hello, my name is #{@name}." end end person = Person.new("Alice") person.greet # Output: Hello, my name is Alice.
4.3 Class Variables
- Starts with @@.
- Shared among all instances of a class.
- Default value is nil.
class Counter @@count = 0 def initialize @@count += 1 end def self.total @@count end end c1 = Counter.new c2 = Counter.new puts Counter.total # Output: 2
4.4 Global Variables
- Starts with $.
- Accessible from anywhere in the program.
- Use with caution, as they can lead to unpredictable behavior.
$global_var = "I'm global" def print_global puts $global_var end print_global # Output: I'm global
5. Practical Examples
5.1 Using Variables in Methods
def greet_user(name) puts "Hello, #{name}!" end greet_user("Alice") # Output: Hello, Alice!
5.2 Swapping Variables
a = 10 b = 20 a, b = b, a puts "a = #{a}, b = #{b}" # Output: a = 20, b = 10
5.3 Variables in Loops
sum = 0 (1..5).each do |number| sum += number end puts sum # Output: 15
5.4 Using Class Variables
class Student @@total_students = 0 def initialize(name) @name = name @@total_students += 1 end def self.total @@total_students end end s1 = Student.new("Alice") s2 = Student.new("Bob") puts Student.total # Output: 2
5.5 Variables with String Interpolation
name = "Ruby" version = "3.0" puts "Welcome to #{name} version #{version}!" # Output: Welcome to Ruby version 3.0!
6. Common Mistakes and Tips
- Avoid Global Variables: They make debugging harder and can lead to conflicts.
- Use Meaningful Names: Choose descriptive names that reflect the variable’s purpose.
- Use Constants for Fixed Values: Constants start with an uppercase letter and should not be reassigned.
MAX_USERS = 100
- Scope Awareness: Understand variable scope (local, instance, class, or global) to avoid unexpected behavior.
7. Summary
Key Points
- Ruby variables do not require explicit type declarations.
- Variable types (local, instance, class, global) determine scope and usage.
- Use meaningful variable names and follow Ruby’s naming conventions.
Best Practices
- Minimize the use of global variables.
- Leverage instance and class variables appropriately in object-oriented programming.
- Use string interpolation for cleaner and more readable code.
By mastering variables in Ruby, you can effectively manage data and build organized, maintainable programs