Variables in Ruby Language
Ruby is a dynamic and versatile programming language known for its simplicity and ease of use. One of the funda
mental concepts in Ruby, as in many programming languages, is the use of variables. Variables are essential for storing and manipulating data in your programs. In this post, we’ll dive into the world of variables in Ruby, exploring their types, naming conventions, and how to use them effectively with practical examples.Variable Types
Ruby has several types of variables:
- Local Variables: Local variables are created by starting the variable name with a lowercase letter or an underscore. They are limited to the scope in which they are defined.
name = "John"
age = 30
- Instance Variables: Instance variables begin with ‘@’ and are used to store object-specific data in Ruby classes.
class Person
def initialize(name)
@name = name
end
end
- Class Variables: Class variables are prefixed with ‘@@’ and are shared among all instances of a class.
class Car
@@total_count = 0
def initialize
@@total_count += 1
end
end
- Global Variables: Global variables start with a dollar sign ‘$’ and can be accessed from anywhere in your Ruby program.
$global_var = 42
- Constant Variables: Constants begin with an uppercase letter and are used to store values that should not be changed during the program’s execution.
MAX_SPEED = 100
Variable Naming Conventions
Ruby has some naming conventions for variables:
- Variable names should use snake_case (e.g., my_variable, user_age) for better readability.
- Start instance variables with ‘@’, class variables with ‘@@’, and global variables with ‘$’.
- Avoid using reserved words, as they have special meanings in Ruby.
Using Variables with Examples
Let’s look at some practical examples of using variables in Ruby:
Local Variables
name = "Alice"
age = 25
puts "My name is #{name} and I am #{age} years old."
Instance Variables
class Person
def initialize(name)
@name = name
end
def say_hello
puts "Hello, my name is #{@name."
end
end
alice = Person.new("Alice")
alice.say_hello
Class Variables
class BankAccount
@@total_balance = 0
def deposit(amount)
@@total_balance += amount
end
def self.total_balance
@@total_balance
end
end
account1 = BankAccount.new
account1.deposit(100)
account2 = BankAccount.new
account2.deposit(200)
puts "Total balance in all accounts: #{BankAccount.total_balance}"
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.