Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Variables and Constants in Ruby
2.1.
Global Variables
2.2.
Instance Variables
2.3.
Class Variables
2.4.
Local Variables
2.5.
Pseudo variables
3.
Object and its Lifetime
3.1.
Debugging Reference
4.
Frequently Asked Questions
4.1.
What is the use of load in Ruby?
4.2.
Name various class libraries in Ruby.
4.3.
Is there any limit on the value of numbers that Ruby can perform?
4.4.
What do you understand by portability in Ruby?
4.5.
What is the primary difference between a module and a class?
5.
Conclusion
Last Updated: Mar 27, 2024

Object Lifetime in Ruby

Author Naman Kukreja
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

For a developer working with classes is a common practice, like he has to implement various classes as he needs to modify various operations. But if he has to use the classes in multiple instances, does he have to create a class every time?

The answer is no. We can use objects as they will have the same variables and properties as the class. This will reduce the code complexity. But can we use objects anywhere in the whole code?

No, we cannot use the object in the whole code. We should know where the object is declared and where it will be accessible within the function. It will be determinable by the object’s lifetime. Don’t worry. We will learn about object lifetime while moving further in the blog, so let’s get on with our topic without wasting time.

Variables and Constants in Ruby

Variables are one of the most crucial features in ruby as they hold the data in the memory location used by any program. There are mainly five types of variables present in Ruby. We will learn all of them in this blog section.

Global Variables

The global variables in ruby begin with the ‘$’ symbol with a lower letter. Global variables can be initialized, and uninitialized global variables will have the value equal to nil and the procedure waring with the -w option.

It can be used within the block of initialization. It will have no scope after the completion of the function. Assigning global variables after the global status is not advisable as they will make the program cryptic. The example of the global variable is shown below:

#!/usr/bin/ruby

 
$global_variable = 10
class Class1
   def print
      puts "Global variable in Class1"
   end
end
class Class2
   def print
      puts "Global variable in Class2"
   end
end

 
class1obj = Class1.new
class2obj = Class2.new
class1obj.print_global
class2obj.print_global

Instance Variables

The instance variables in Ruby begin with @ symbol, as the name suggests. It belongs to one instance of the class.

Instance variables can be initialized, and uninitialized instance variables will have the value equal to nil and the procedure waring with the -w option. Any instance can access it within the method. Most of the time, we only have limited access to a particular class instance. They can be used without initialization.

#!/usr/bin/ruby

 
class Customer
   def initialize(id, name, addr)
 @cust_name = name     
 @cust_id = id
    @cust_addr = addr
   end
   def display_details()

 
      puts "Customer name #@cust_name"
 puts "Customer id #@cust_id"
      puts "Customer address #@cust_addr"
   end
end

 
# Create Objects
cust1 = Customer.new("Wisdom Apartments", "John",1, Mumbai")
cust2 = Customer.new(" New Empire road"."Poul",2 , Delhi")

 
# Call Methods
cust1.display_details()
cust2.display_details()

Class Variables

They begin with @@ characters and need to be initialized before using in the methods. As the name suggests, they are class variables, so they belong to the whole class and can be used from anywhere in the class. Due to their availability in the whole class, if their value is changed at one instance, then their value will be changed for every other instance in the class.

The reference to an uninitialized class variable will throw an error. The class variables will be shared among all the descendants of the class. Overriding the class variables will issue -w warning.

#!/usr/bin/ruby

 
class Customer
@@no_of_customers = 0
   def initialize(id, name, addr)
 @cust_name = name     
 @cust_id = id
    @cust_addr = addr
   end
   def display_details()

 
      puts "Customer name #@cust_name"
 puts "Customer id #@cust_id"
      puts "Customer address #@cust_addr"
   end
end

 
# Create Objects
cust1 = Customer.new("Wisdom Apartments", "John",1, Mumbai")
cust2 = Customer.new(" New Empire road"."Poul",2 , Delhi")

 
# Call Methods
cust1.display_details()
cust2.display_details()

Local Variables

They begin with an underscore (_) or lowercase letters. The local variables' scope varies from module to class and corresponding end. In short form, opening brace({) to closing brace(}).

When a user refers to an uninitialized local variable, the compiler refers to this call as a call to a method with no argument. We can use the assignment to the variables as declarations to the variables. The variables will be available until the scope of variables exists. The examples of local variables are id, addr, and name in the above example.

Pseudo variables

These unique variables are represented as local variables but behave like constants. As they are constant, you cannot assign any value to them.

  • True: Value represents true.
  • False: Value representing false.
  • Self: The receiver object to the current object.
  • _LINE_: The current line number in the source file.
  • _FILE_: The name of the current source file.
  • Nil: Value representing undefined.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Object and its Lifetime

Before diving into objects, we will briefly introduce the class.

Ruby is an object-oriented programming language, and in object-oriented programming languages, a class is essentially a template with data that contains the behavior and information. Now we will learn about objects. They are the default root of all the classes. These are the copies with all the class features it points to.

We can create multiple objects of the same class. Methods of the class will be available to all the created objects.

You can create a class in Ruby by following the below-given method:

class mobilegame
end 

And with the creation of a class, you can add the new data types in the class shown below:

class mobilegame
attr_accessor: name, studio, genre, price
end

We can also initialize these values by using an object. We will create the object of the mobilegame class and then use the object to fill the value of attributes individually like, as shown below:

class Mobilegame
attr_accessor: name, studio, genre
end
mobilegame1 = Mobilegame. new()
mobilegame1.name = "GTA San Andreas."
videogame1.studio = "CD Projekt Red"
mobilegame1.genre = "RPG"
mobilegame1.price = "$50"

 

In the above example, we have created an object called mobilegame1 and then used it. Operator to initialize the value of each attribute.

You can call new objects using initialize method. We can also add different methods to our class:

Mobilegame
attr_accessor: name, studio, genre
def initialize(name, studio, genre)

 
 @studio = studio
 @name = name
 @genre = genre
end
def on_sale
 # will return a boolean value
end
end

The object of every class needs to be created explicitly. Mostly they are created by using the new keyword. With the help of this method, it allocates the memory to the newly created object, then initializes the state of the new object aerated as empty by using the initialize method.

Most classes define their own initialize method for the initiation of various objects.

The initialize and new methods are the default ways for creating new classes, but classes can also define other methods that return instances, known as "factory methods." We'll better understand the new, initialize, and factory methods.

Unlike in languages like C and Java, Ruby objects never need to be explicitly deallocated.

C++ Garbage collection is a Ruby approach for automatically destroying things that aren't required. When an object is marked as a candidate for garbage, It becomes unreachable as there are no references to the object other than the one it was created with other inaccessible items.

Because Ruby employs garbage collection, Ruby programs are less prone to memory leaks than programs written in languages that rely on objects. If the cache isn't purged using a least-recently-used algorithm, If you use the hash algorithm, cached items will remain reachable as long as the hash is reachable if the hash is used as a reference.

Debugging Reference

Let’s understand this with an example. Below is a code that contains some errors, so we will try to find out the errors in the below-given code:

class Mobilegame
attr_accessor: name, studio, genre, price
def initialize(name, studio, genre, price)
 @name = name
 @studio = studio
 @genre = genre
 @price = price
end
def rpg_game
 if @genre == "RPG"
   true
 else
   false
 end
end
def indie_game
  if @studio == indie
   true
  else
   false
  end
end
end

Running the above code will throw an error as we haven't defined a method that will allow ruby to understand whether this method is independent or required to run on code studio.

Frequently Asked Questions

What is the use of load in Ruby?

In Ruby, the load command is used to load the available code into the current code.

Name various class libraries in Ruby.

Various class libraries in Ruby are

  • Text Processing
  • Network Programming
  • XML Programming
  • CGI Programming
  • GUI Programming.

Is there any limit on the value of numbers that Ruby can perform?

No, there is no barrier to the limit of number. The number can be large ruby will process it accordingly using bignum and fixnum classes.

What do you understand by portability in Ruby?

The Ruby language can be ported to many platforms. The programs of ruby language can be ported without any modification in the source code.

What is the primary difference between a module and a class?

A module cannot be instantiated or subclassed, whereas a class cannot implement mixins.

Conclusion

In this article, we have discussed variables and constants with proper explanations of each type of variable with examples and the method to create them, followed by objects and their lifetime, and at last by debugging errors in the code.

If you have any doubts regarding why you should use ruby, then visit this blog here, and you will get your answers. And for any further queries regarding Ruby, you can visit here. You will get answers to almost all of your queries.

If you are looking for any guided path for proper practice of any framework or language, you can refer to our guided paths. And suppose you are looking to learn any language, DSA, Competitive Programming, Computer Subjects, or framework. In that case, you can always rely on our paid courses which will give you industry-level knowledge.

 “Happy Coding!”

Previous article
Object References in Ruby
Next article
Object identity in ruby
Live masterclass