Variables & Scope

💎 Ruby Lesson 2 Beginner

In Ruby, variable scope is determined by prefix naming conventions. Type declaration keywords are not required; variable types are resolved dynamically at runtime.

1 Scope Prefixes & Constants

Ruby manages scopes using naming prefixes:

  • Local Variable (`age`): Declared with lowercase characters. Only accessible inside its declaring function or block.
  • Instance Variable (`@age`): Prefixed with a single `@`. Accessible across methods inside a class instance.
  • Class Variable (`@@count`): Prefixed with a double `@@`. Shared across all instances of a class.
  • Global Variable (`$debug`): Prefixed with a `$`. Accessible from anywhere in the application.
  • Constants (`PI`): Start with an **uppercase letter**. Ruby will warning you if you try to reassign a constant, but will still allow the program to run.
2 Variables Code

Let's run a program declaring local variables, globals, and constants:

Ruby — Variables ▶ Run Code
# Local variables
name = "Balaji"
age = 22

# Constant declaration (starts with capital letter)
GRAVITY = 9.8

# Global variable
$app_mode = "Production"

puts "Name: #{name}"
puts "Constant Gravity: #{GRAVITY}"
puts "Global Mode: #{$app_mode}"
3 Code Challenge
Challenge: Write a script that declares a constant. Try to reassign a new value to it and print it. Check the output in the compiler to see the warning message Ruby outputs.