Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Defining Methods with define_method
3.
Defining Methods with class_eval and instance_eval
4.
Frequently Asked Questions
4.1.
What is define_method Ruby?
4.2.
What is metaprogramming in Ruby?
4.3.
What is method_missing in Ruby?
4.4.
Is Ruby dynamic typed?
4.5.
What is monkey patching in Ruby?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Dynamically Creating Methods in Ruby

Author Abhay Trivedi
0 upvote

Introduction

We use def keywords to describe methods, which is acceptable in most situations. However, if you have to develop several techniques, each with the same fundamental structure and logic, it looks repetitive and not at all dry. Ruby allows for the instant creation of methods due to its dynamic nature.

Dynamically Creating Methods in Ruby

Let's take an example for better understanding:

class A
    define_method :a do
      puts "hello"
    end

    define_method :greeting do |message|
      puts message
    end
  end

  A.new.a #=> hello
  A.new.greeting 'Ninja' #=> Ninja
You can also try this code with Online Ruby Compiler
Run Code

 

The above code gives the following output:

Dynamically Creating Methods in Ruby example code output

Defining Methods with define_method

We can use “define_method” for dynamically creating methods in ruby. The define_method defines a receiver-based instance method. A Proc, a Method, or an UnboundMethod object can be used as the method argument.

Let's see an example of define_method for dynamically creating methods in ruby.

Here is an example of code without define_method.

class User
    ONLINE = 0
    OFFLINE = 1
    PENDING = 2

    attr_accessor :status

    def online?
      status == ONLINE
    end

    def offline?
      status == User::OFFLINE
    end

    def pending?
      status == User::PENDING
    end
    
  end

  user = User.new
  user.status = 1

  puts user.offline?
  #=> true
  puts user.online?
  #=> false
You can also try this code with Online Ruby Compiler
Run Code

 

The above code gives the following output:

define_method output

 

Using the define_method, the above code can be written as:

class User

    ONLINE = 0
    OFFLINE = 1
    PENDING = 2

    attr_accessor :status

    [:online, :offline, :pending].each do |method|
      define_method "#{method}?" do
        status == User.const_get(method.upcase)
      end
    end

  end

  user = User.new
  user.status = 1

  puts user.offline?
  #=> true
  puts user.online?
  #=> false
You can also try this code with Online Ruby Compiler
Run Code

 

The output of the code above where define_method is used is shown below.

define_method output

Defining Methods with class_eval and instance_eval

Additionally, there are instance eval and class eval, which can be used to create methods in ruby dynamically. These techniques enable the evaluation of any piece of code inside the context of a particular class or object. Using class_eval like this becomes liable to the slight overhead of parsing the code string. However, the benefit is that the methods we define need not use reflective APIs; they can query or set the value of an instance variable directly.

Let’s see an example of how class_eval and instance_eval can be used.

Foo = Class.new
  Foo.class_eval do
    def class_bar
      "This class_bar"
    end
  end
  Foo.instance_eval do
    def instance_bar
      "This instance_bar"
    end
  end
puts  Foo.new.class_bar   #=> "For class_bar"
puts   Foo.instance_bar       #=> "For instance_bar"
You can also try this code with Online Ruby Compiler
Run Code

 

The above code gives the following output:

class_eval output

Frequently Asked Questions

What is define_method Ruby?

You may utilize the define method_method in the Module class to dynamically generate methods. When using define_method, you use it with the name of the new method and a block, and the block's parameters become the new method's parameters.

What is metaprogramming in Ruby?

When using metaprogramming, code interacts with other code instead of data. It may be used to create programs that generate code as needed during execution. Ruby can open and change classes, make methods on the fly, and do much more thanks to metaprogramming.

What is method_missing in Ruby?

method_missing is a means to manage circumstances when you call a method that doesn't exist that Ruby gives you access to the inside of your objects. Like a Begin/Rescue for method calls, kind of. It provides one final opportunity for you to handle that method call before an exception is triggered.

Is Ruby dynamic typed?

Because Ruby is a dynamic language, types are verified as the code is executed. The compiler won't alert you if you attempt to call a method on an object that doesn't exist; instead, you'll learn about the issue when the code is run and receive a NoMethodError.

What is monkey patching in Ruby?

A Monkey Patch (MP) is a term used in Ruby to describe a dynamic alteration to a class, which may introduce new methods or replace existing ones. Ruby offers this capability to provide programmers additional freedom.

Conclusion

In this article, we have discussed Dynamically Creating Methods in ruby. We saw how we can use define_method and class_eval methods for dynamically creating methods in Ruby.

After reading about the files and directories in ruby, are you not feeling excited to read/explore more articles on the topic of DSA? Don't worry; Coding Ninjas has you covered. To learn, see Try Ruby, the History of Ruby and Constants in Ruby.

Here are more articles to the rescue:

 

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!

Happy Learning!

thankyou from coding ninjas

Live masterclass