Ruby Variables
In Ruby, variables are used to store and manipulate data. A variable is a container that holds a value, and you can change or update its value at any point in the program.
Syntax
To create a variable in Ruby, you use the variable assignment operator =
and assign a value to the variable. Ruby does not require you to declare the type of the variable.
variable_name = value
Example
name = "John"
age = 30
is_male = true
puts "My name is #{name}, and I am #{age} years old. I am a male? #{is_male}"
Output
My name is John, and I am 30 years old. I am a male? true
Explanation
In the example above, we created three variables name
, age
, and is_male
, and assigned values to them. We then used the variables to construct a string by interpolating them with the #{}
syntax.
Variable Types
In Ruby, there are four types of variables:
- Local variables: Local variables are variables that are defined and used inside a block or a method. They have a limited scope and cannot be accessed outside the block or method where they are defined.
- Instance variables: Instance variables are variables that are defined at the class level and can be accessed across different methods of an object.
- Class variables: Class variables are variables that are defined at the class level and can be accessed across different objects of a class.
- Global variables: Global variables start with a
$
symbol and can be accessed from anywhere in the program.
Important Points
- A variable is a container that holds a value in Ruby.
- Ruby variables are dynamic; they do not require type declarations.
- Ruby has four types of variables: local, instance, class, and global variables.
Summary
Ruby variables are used to store and manipulate data. You can create different types of variables in Ruby based on your needs, and change their values at any point in the program. Understanding the different types of variables in Ruby and their scope is important to write efficient and maintainable code.