Table of contents
1.
Introduction
1.1.
Problem 🕵️‍♀️
1.2.
Solution
2.
Explanation🧠
3.
Frequently Asked Questions
3.1.
What is a class in Ruby?
3.2.
How do Ruby classes work?
3.3.
When should you use a class in Ruby?
3.4.
What is the difference between the class variable and instance variable?
3.5.
What is the difference between modules and classes *?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

Managing Class data in ruby

Author Amit Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will learn how to manage class data in the Ruby programming language.

Class variables are also called static variables. They are declared with the static keyword in a class but outside a method, constructor, or block. Instance variables are generally created when an object is made by using the keyword 'new' and destroyed when the object is destroyed.

ruby

Problem 🕵️‍♀️

We wish to save a small amount of data with the class itself rather than storing the bit of data with each instance of the class.

Solution

Class variables have two at signs before them, whereas instance variables only have one. An instance variable, as well as a class variable, is present in this class:

class Bike
    @make
    @@wheels = 2
 
    def initialize(make)
        @make = make
    end
 
    def self.wheels
        @@wheels
    end
    attr_accessor :make
end
 
# outside of the class 
panigale = Bike.new("Ducati")

# instance variable is called on the ob
puts panigale.make
 
# class variable is called on the class
puts Bike.wheels
You can also try this code with Online Ruby Compiler
Run Code

 

Output

output

Explanation🧠

Class variables hold data that is relevant to the class itself or to each instance of the class. They are frequently used to regulate, stop, or respond to the instantiation of the class. In Ruby, a class variable functions similarly to a static variable in Java.

Let’s see an example in which we will try to use a class variable and a class constant so that we can regulate how and when a class instantiation is done:

Code:

class Test
    THINGS = ['Rock', 'Paper', 'Scissors'].freeze
    @@number_instantiated = 0
    def initialize
    if @@number_instantiated >= THINGS.size
        raise ArgumentError, 'Sorry, we only had three.'
    end
    @name = THINGS[@@number_instantiated]
    @@number_instantiated += 1
    puts "Let's go for… #{@name}!"
    end
end
 
Test.new
 
Test.new

Test.new
 
Test.new
You can also try this code with Online Ruby Compiler
Run Code

 

Output:

output

Writing setter or getter methods for class variables are not regarded as being appropriate. Apart from useful constants and those you can expose via class constants, like NAMES in the example above, you won't often need to disclose any class-wide information.

The following class-level Module#attr_reader and Module#attr_writer counterparts can be used if you do not wish to write setter or getter methods for class variables.

In order to define new accessor methods, they employ metaprogramming:

class Module
    def class_attr_reader(*symbols)
        symbols.each do |symbol|
            self.class.send(:define_method, symbol) do
                class_variable_get("@@#{symbol}")
            end
        end
    end
 
    def class_attr_writer(*symbols)
        symbols.each do |symbol|
            self.class.send(:define_method, "#{symbol}=") do |value|
                class_variable_set("@@#{symbol}", value)
            end
        end
    end
    
    def class_attr_accessor(*symbols)
        class_attr_reader(*symbols)
        class_attr_writer(*symbols)
    end
end
You can also try this code with Online Ruby Compiler
Run Code

Here, the Test class is given an accessor for its class variable using Module#class_attr_reader in this instance.

Test.number_instantiated
# NoMethodError: undefined method 'number_instantiated' for Test:Class
You can also try this code with Online Ruby Compiler
Run Code

Output:

output

 

class Test
    class_attr_reader :number_instantiated
end
Test.number_instantiated                            # => 3
You can also try this code with Online Ruby Compiler
Run Code

 

Both a class variable foo and an instance variable foo are permissible, but doing so will make things more difficult for you. The accessor method foo, for instance, must retrieve either one or the other. attr_accessor: foo followed by class attr_accessor: foo will discreetly replace the instance version with the class version.

Similar to instance variables, class variables can be used directly with class_variable_get and class_variable_set by avoiding encapsulation. Similar to instance variables, this should only be done from within the class, typically inside of a define_method call.

Check out this article - Compile Time Polymorphism

Frequently Asked Questions

What is a class in Ruby?

Ruby is an object-oriented programming (OOP) language. The features of an object-oriented programming language (OOP) include data encapsulation, polymorphism, inheritance, data abstraction, operator overloading, etc. In object-oriented programming, classes and objects play an important role.

How do Ruby classes work?

In Ruby, a class is like an object that defines a blueprint to create other objects. Classes define which methods are available in any instance of that particular class. When we define a method inside a class, it creates an instance method on that particular class. Any future instance of that particular class will have that method available.

When should you use a class in Ruby?

Generally, a class should be used for the functionality that needs instantiation or that needs to keep track of states. A module can be utilized either as a way for mixing functionality into multiple classes or as a way for providing one-off features that don't need to be instantiated or to keep track of state.

What is the difference between the class variable and instance variable?

Class variables, also known as static variables, are declared with the static keyword in a class but outside a method, constructor, or block. Instance variables are generally created when an object is made with the use of the keyword 'new' and removed when the object is destroyed.

What is the difference between modules and classes *?

A class is more like a unit, and a module is like a loose collection of stuff like functions, classes, or variables. In a public module, the classes in that particular project have access to all the functions and variables of that module. We don't have to specify the module name to address one.

Conclusion

In this article, we learned how to manage class data in ruby. After reading about management of class data in Ruby, are you not feeling excited to read/explore more articles on the topic of Ruby? Don't worry; Coding Ninjas has you covered. To learn, see Object Marshalling in RubyTainting Objects in Ruby, and Object References in Ruby.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

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

Merry Learning

Live masterclass