Dynamically defining methods with define_method in Ruby


Created by Stan on 07-04-2023


define_method is a method that allows you to define methods on a class at runtime. You can use this technique to generate methods on the fly, modify existing methods, or create methods based on user input. In this article, we'll explore define_method and its various use cases using a Book class as an example.

To use define_method in Ruby, you call it on a class and pass in a method name and a block of code. Here's an example of using define_method to generate a title method for our Book class:

class Book
  def initialize(title, author)
    @title = title
    @author = author
  end

  define_method :title do
    @title
  end
end

book = Book.new("Animal Farm", "George Orwell")
puts book.title #=> "Animal Farm"

You can also use define_method to modify existing methods on a class. Here's an example of using define_method to modify the title method to always return the title in uppercase:

class Book
  def initialize(title, author)
    @title = title
    @author = author
  end

  define_method :title do
    @title.upcase
  end
end

book = Book.new("Animal Farm", "George Orwell")
puts book.title #=> "ANIMAL FARM"

define_method can also be used to create methods based on user input. Here's an example of using define_method to generate a method based on a user-provided argument:

class Book
  def initialize(title, author)
    @title = title
    @author = author
  end

  def self.create_method(method_name)
    define_method method_name do
      "#{@title} by #{@author}"
    end
  end
end

book = Book.new("Animal Farm", "George Orwell")
Book.create_method("description")
puts book.description #=> "Animal Farm by George Orwell"

define_method is a powerful technique in Ruby that allows you to define methods dynamically at runtime. You can use it to generate methods on the fly, modify existing methods, or create methods based on user input. By using define_method, you can make your code more flexible and dynamic.



Related Posts