Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
241: define_method vs def for Dynamic Methods
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_RATESas 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_methodto iterate over theEXCHANGE_RATEShash 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.0There are no comments for now.