Table of contents
1.
Introduction
1.1.
Classes in Ruby
1.2.
Module in Ruby
2.
Problem statement
2.1.
Duck typing
2.2.
Class typing
3.
Frequently asked questions
3.1.
Can the definition of a class be repeated?
3.2.
What is an instance variable of a class?
3.3.
How do class variables and class instance variables differ from one another?
3.4.
What differentiates a class from a module?
3.5.
Can modules be subclassed?
4.
Conclusion
Last Updated: Mar 27, 2024

Checking Class or Module Membership in ruby

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

Introduction

In this article, we are going to learn about how we can check whether an object is of the right type in order to interact with a particular class or module in Ruby. But before diving into that, let's first have some brief about the Ruby classes and module just to have a better understanding.

Ruby Introduction

Ruby is a dynamic and purely object-oriented programming language that was developed by Yukihiro Matsumoto. It is a high-level programming language with much easier syntax so that it can be learned easily. 

Now, what is a class in Ruby? A class is like a template for the program code that can be accessed through an instance object of the class. We can implement various methods in a class according to our requirements. 

Classes in Ruby

Class in Ruby

In Ruby, we use the class keyword to initialise the class with the class name where the first letter of the class should be capitalised, and within the class, we can add some code and close with an end keyword.
 

Syntax

class Name_of_class
    #statement
end
You can also try this code with Online Ruby Compiler
Run Code

 

Example

class Alert 
    def display_message
        puts 'welcome to coding ninjas'
    end 
end 

#object creation
obj = Alert.new

#calling the method with the object
obj.display_message
You can also try this code with Online Ruby Compiler
Run Code

 

Output

Output

Module in Ruby

Module in Ruby

A module is a compilation of class variables, methods and constants. Unlike class we do not need objects to access the module data. All the classes are modules but not all modules are classes.

 

Syntax for module

It initialises with the module keyword with the name of the module and the first letter should be capitalised.

module Name_of_module
    #statements
end
You can also try this code with Online Ruby Compiler
Run Code

 

Example

module Display
    # method in module should have the prefix of module name
    def Display.message
        puts 'here is the displayed message'
    end 
end 
 
#calling the message method in module
Display.message
You can also try this code with Online Ruby Compiler
Run Code

 

Output

Output

Problem statement

Our main goal is to check whether the object is of the right type for the class or module methods. There are ways through which we can check that or we can say there are two typing techniques to do that.

Duck typing

Duck typing

source

Duck typing is a programming typing technique used in Ruby. As you know, in Ruby, there is no need to specify the datatype of the object like in many other programming languages. We can just declare a variable and assign a value to it. So in duck typing, we do not check the class. Instead, we check how that particular object will respond to an operator or to a method(object.respond_to? Operator or method_name). If that object supports the Operator or method, then that object is right for the purpose.

 

Example

class Ducktyping
    #declaring the method
    def objectchecking(x)
        #checking object x response to upcase and to_i method.
        puts 'object class is:',x.class
        puts x.respond_to? :upcase 
        puts x.respond_to? :to_i
    end 
end 
 
obj = Ducktyping.new 
obj.objectchecking('hello')
obj.objectchecking(5)
obj.objectchecking(true)
You can also try this code with Online Ruby Compiler
Run Code

 

Output

Output

In the above example, we can observe how the different types of objects are responding to the method upcase and to_i. The upcase method converts the string into uppercase and to_i converts the number to an integer and string also. In the output string object is responding true for both the methods. This means that the string object is compatible with both methods. Second, an integer object is true only for to_i, not with an upcase method, and boolean is false for both. 

Class typing

In class, what we do is we just type the logic of the program where we can check whether that particular object belongs to a particular data type or class or not (object.is_a?classtype).

 

Example

class Classtyping
    #declaring the method
    def objectchecking(x)
     #checking the class of object x
        if x.is_a?String
            puts "welcome #{x}"
        else
            puts 'object x does not belong to string class'
        end 
    end 
end 

obj = Classtyping.new 
obj.objectchecking('Ninja')
obj.objectchecking(10)
obj.objectchecking(true)
You can also try this code with Online Ruby Compiler
Run Code

 

Output

output

In the above example we only want to print an object on the console if it belongs to the string class. That's how the class typing works in programming. Where we are considerate about the object class.
 

Though it is generally advised to use duck typing in most of the cases because of the functionality it provides, it is also necessary to use class typing with duck typing so that the functionality of the code can become better.

 

Example

def append_objects(obj)
    unless obj.respond_to? :<<
      puts "cannot be appended"
    end
    if obj.is_a?Numeric 
        puts "cannot append a number"
    else 
    puts obj << obj
    end
end

append_objects('CodingNinjas')
append_objects(4)
You can also try this code with Online Ruby Compiler
Run Code

 

Output

output

In the above example we can see that we can append a string with the << operator. We can also use a number with the << operator but it does not get appended as it is supposed to. It will return a multiplied value for a number like for 4 it will give us 64 so that we have to use Is_a to exclude the number objects in the program. That is how we can use both types of techniques in a program.

Frequently asked questions

Can the definition of a class be repeated?

A class can have multiple definitions. Every definition is combined with the previous one. The previous technique is replaced and lost if it is redefined.

What is an instance variable of a class?

@instances is a class instance variable in this case. It belongs to the class object Entity, which is an instance of the class Class, not to an instance of the class Entity. Only the class's class methods have direct access to class instance variables.

How do class variables and class instance variables differ from one another?

The major distinction is how class variables behave in relation to inheritance: class variables are shared by a class and all of its subclasses, whereas class instance variables are exclusive to a single class. Within the framework of an inheritance hierarchy, class variables can be conceptualized in some ways as global variables, complete with all the drawbacks that global variables have. For instance, any of a class's subclasses might (accidentally) reassign a class variable, which would affect all other classes.

What differentiates a class from a module?

Methods and constants are gathered in modules. They are unable to produce instances. Classes have a per-instance state and can produce instances (objects) (instance variables). Classes and other modules may contain a mix of modules. Constants and methods from the merged module are incorporated into the class's own, enhancing its functionality. However, classes cannot be combined with anything. A class can't inherit from a module, although it may from another class. You cannot inherit from a module.

Can modules be subclassed?

A module can have no subclasses.

Conclusion

In this article, we learned we can check whether an object is of the right type for a particular class method or module method with the help of the two techniques duck typing and class typing that we can use altogether to write a much better logic.

To learn about more ruby please look into the following articles:

 8 reasons why ruby should be your first language

Ruby and ruby on rails: differences between them

Ruby on rails

To learn more about DSA, competitive coding and many more knowledgeable topics, please look into the guided paths on Coding Ninjas Studio. Also, you can enroll in our courses and check out the mock test and problems available to you. Please check out our interview experiences and interview bundle for placement preparations.

Please upvote our blog to help other ninjas grow.

Happy Learning

Live masterclass