Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Characteristics of Instance Variables
2.
Automatic Initialization of Instance Variables
3.
Frequently Asked Questions
3.1.
What is @instance_variables in Ruby?
3.2.
What are the different types of variables in Ruby?
3.3.
What is an instance of a class in Ruby?
3.4.
What happens if you reference a class variable in Ruby?
3.5.
What is instance method in Ruby?
4.
Conclusion
Last Updated: Mar 27, 2024

Automatically Initializing Instance Variables in Ruby

Author soham Medewar
0 upvote

Introduction

In Ruby, variables are classified into four types: local variables, instance variables, class variables, and global variables. In Ruby, an instance variable has a name that begins with the @ symbol, and its content is limited to whatever the object itself references to. Even though two objects belong to the same class, they can have distinct values for their instance variables.

Characteristics of Instance Variables

  • Before initialization, the instance variable has the value nil.
  • By default, all instance variables are private.
  • The instance variables of an object can only be accessed through the object's instance methods.
  • Ruby instance variables do not need to be declared. This means that the object structure is adaptable.
  • When an object is first referenced, every instance variable is dynamically attached to it.
  • An instance variable belongs to the object (each object has its own instance variable of that specific class). One instance object can change the values of its instance variables without affecting any other instances.
  • Except when the method is regarded as static, an Instance variable can be utilized by numerous class methods.  

 

When you write a constructor for a class that takes several arguments, where each argument is assigned to an instance variable. For example, there is an RGBColor class that has three instance variables, i.e., red, green, and blue. To assign a value to each of the instance variables, we need to write the following code.

class RGBColor(red=0, green=0, blue=0)
@red = red
@blue = blue
 @green = green
end
You can also try this code with Online Ruby Compiler
Run Code

 

You'd like to avoid all of the typing required to complete those variable assignments.

Automatic Initialization of Instance Variables

To overcome the above-discussed problem there is a method that helps us to automatically initialize the instance variables. It takes as an argument the list of variables supplied to the initialize method, as well as the variables' binding to values. You can avoid the time-consuming variable assignments by using this method:

Code

class Object
    def set_instance_variables(binding, *variables)
        variables.each do |var|
        instance_variable_set(:"@#{var}", eval(var.to_s, binding))
        end
    end
end
class RGBColor
    def initialize(red=0, green=0, blue=0)
        set_instance_variables(binding, *local_variables)
    end
end
RGBColor.new(255, 0, 255)
You can also try this code with Online Ruby Compiler
Run Code

 

Our set instance variables method, accepts a list of parameter names to be converted into instance variables, as well as a Binding containing the values of those arguments at the time of the method call. An eval statement binds the corresponding instance variable to the corresponding value in the Binding for each argument name.

Since the names of a method's parameters are not available from Ruby code, how can we obtain that list?  When you call a method, any arguments you give in are immediately bound to local variables. These are the only local variables defined at the start of the method.

When you call a method, any arguments you pass in are immediately bound to local variables. These are the only local variables defined at the start of the method. This means that at the start of a method, invoking Kernel#local variables will return a list of all the parameter names.

If your function accepts parameters that you do not want to set as instance variables, just delete their names from the list returned by Kernel#local variables before passing it to set instance variables:

Code

class RGBColor
    def initialize(red=0, green=0, blue=0, debug=false)
        set_instance_variables(binding, *local_variables-['debug'])
        puts "Color: #{red}/#{green}/#{blue}" if debug
    end
end
RGBColor.new(10, 200, 255, true)
You can also try this code with Online Ruby Compiler
Run Code

Frequently Asked Questions

What is @instance_variables in Ruby?

In Ruby, an instance variable has a name that begins with the @ symbol, and its content is limited to whatever the object itself references to. Even though two objects belong to the same class, they can have distinct values for their instance variables.

What are the different types of variables in Ruby?

In Ruby, variables are classified into four types: instance variables, local variables, class variables, and global variables.

What is an instance of a class in Ruby?

A class in Ruby is an entity that defines a blueprint for creating other objects. Classes specify which methods are available to any class instance. Defining a method within a class results in the creation of an instance method for that class.

What happens if you reference a class variable in Ruby?

Before they can be used, class variables must always have a value given to them. If you refer to a class variable that has no value, Ruby throws a NameError.

What is instance method in Ruby?

A method in Ruby adds functionality to an Object. A class method gives functionality to the class as a whole, whereas an instance method provides functionality to a single instance of a class.

Conclusion

In this article, we have learned to automatically initialize the instance variable in Ruby.

If you want to learn more, check out our articles on Object Marshalling in RubyTainting Objects in RubyCopying Objects In RubyHow To Invoke Global Functions In Ruby?, and Object References in Ruby.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning, Ninjas!

Live masterclass