How To Declare A Variable In Ruby

Variables are a fundamental concept in any programming language, and Ruby is no exception. They allow you to store and manipulate data in your programs. In this blog post, we’ll show you how to declare a variable in Ruby and discuss the different types of variables available to you. Let’s get started!

Declaring a Variable in Ruby

In Ruby, declaring a variable is as simple as assigning a value to a name. You don’t need to specify the type of the variable, as Ruby is a dynamically-typed language. The syntax for declaring a variable in Ruby is as follows:

variable_name = value

For example, if you want to declare a variable called greeting and assign the value ‘Hello, world!’ to it, you would write:

greeting = ‘Hello, world!’

Types of Variables in Ruby

Ruby has four different types of variables:

  1. Local variables
  2. Instance variables
  3. Class variables
  4. Global variables

1. Local Variables

Local variables are the most common type of variable in Ruby. They are accessible only within the scope they are defined in, such as a method or a block. Local variables start with a lowercase letter or an underscore.

def say_hello
greeting = ‘Hello, world!’
puts greeting
end

say_hello # Outputs ‘Hello, world!’

2. Instance Variables

Instance variables are used within instances of a class. They are accessible throughout the class and allow you to store values that are specific to each object. Instance variables start with an @ symbol.

class Person
def initialize(name)
@name = name
end

def introduce
puts “Hello, my name is #{@name}.”
end
end

person = Person.new(‘Alice’)
person.introduce # Outputs ‘Hello, my name is Alice.’

3. Class Variables

Class variables are used to store values that are shared among all instances of a class. They are accessible throughout the class and its subclasses. Class variables start with two @@ symbols.

class Vehicle
@@number_of_vehicles = 0

def initialize
@@number_of_vehicles += 1
end

def self.count
puts “There are #{@@number_of_vehicles} vehicles.”
end
end

car = Vehicle.new
bike = Vehicle.new
Vehicle.count # Outputs ‘There are 2 vehicles.’

4. Global Variables

Global variables are accessible from anywhere in your Ruby program. They are created by assigning a value to a variable name that starts with a $ symbol. However, the use of global variables is generally discouraged, as they can make your code harder to understand and maintain.

$global_variable = ‘I am a global variable!’

def show_global
puts $global_variable
end

show_global # Outputs ‘I am a global variable!’

Conclusion

Now you know how to declare a variable in Ruby and are familiar with the different types of variables available to you. Remember to choose the appropriate type of variable based on the scope and purpose of the data you’re working with. Happy coding!