Skip to Content
Course content

241: define_method vs def for Dynamic Methods

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this mistake countless times when developers first try to dry up their code. You have a list of similar behaviors, and you think, "Why write five methods that do almost the same thing? I'll just loop through an array and define them on the fly."

class User
  ROLES = [:admin, :editor, :viewer]

  ROLES.each do |role|
    def "#{role}?"
      self.role == role
    end
  end
end

The Syntax Error That Stops Everything

If you try to run that code, Ruby is going to throw a SyntaxError immediately. It doesn't even get to the point of executing the loop. Why? Because def is a keyword, not a method. It expects a literal method name to follow it. You cannot pass a variable or a string interpolation to def and expect Ruby to "figure out" what name you want.

When you're writing standard Ruby, def is great because it's fast and clear. But def is static. It is processed when the class is first loaded. If you need your method names to be determined by data—like that ROLES array—you need a different tool.

Letting Ruby Handle the Dynamic Naming

This is where define_method comes in. Unlike def, define_method is actually a method itself (defined on the Module class). Because it's a method, you can pass it a symbol or a string as an argument, and Ruby will use that as the name for the new method.

Here is how we fix our User class:

class User
  attr_accessor :role
  ROLES = [:admin, :editor, :viewer]

  ROLES.each do |role_name|
    define_method("#{role_name}?") do
      self.role == role_name
    end
  end
end

user = User.new
user.role = :admin
puts user.admin? # => true
puts user.editor? # => false

Notice that we are passing a block to define_method. That block becomes the body of the method. This feels slightly more verbose than a standard def, but it gives us the power to generate an arbitrary number of methods based on any data source we want.

The Secret Weapon: Closures

There is one more critical difference that often trips people up: scope. define_method creates a closure. This means it "remembers" the local variables that were present when it was defined.

In the example above, the role_name variable is a local variable inside the each block. Because define_method captures that scope, the admin? method "remembers" that its role_name was :admin, and the editor? method remembers its was :editor.

If you were somehow able to use def inside a loop, it wouldn't have this memory. def starts a completely fresh scope. I'll keep it simple: if you need to use a variable from the surrounding loop inside your dynamic method, define_method is your only real option. It’s a powerful pattern, but use it sparingly—too many dynamic methods can make your code harder to grep and a bit more mysterious for the next developer who inherits your project.




📋 Practical Task

Building a Dynamic Currency Converter

You are building a PriceConverter class. Instead of writing a separate method for every currency in the world, you need to define them dynamically based on a set of exchange rates.

Your Task:

  • Create a class called PriceConverter.
  • Inside the class, define a constant EXCHANGE_RATES as a hash where the keys are currency codes (e.g., :eur, :gbp, :jpy) and the values are the multipliers relative to USD (e.g., { eur: 0.92, gbp: 0.79, jpy: 150.12 }).
  • Use define_method to iterate over the EXCHANGE_RATES hash and create methods named after the currency (e.g., to_eur, to_gbp).
  • Each dynamic method should take one argument (usd_amount) and return the amount multiplied by that currency's specific rate.

Example Usage:

converter = PriceConverter.new
converter.to_eur(100) # Should return 92.0
converter.to_jpy(100) # Should return 15012.0
Rating
0 0

There are no comments for now.

to be the first to leave a comment.