0
0
Rubyprogramming~10 mins

Define_method with closures in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Define_method with closures
Start
Define method with define_method
Method captures closure variables
Call method
Method uses captured variables
Return result
End
Shows how define_method creates a method that remembers variables from its surrounding context (closure) and uses them when called.
Execution Sample
Ruby
class Greeter
  def initialize(name)
    @name = name
    self.class.define_method(:greet) do
      "Hello, #{@name}!"
    end
  end
end

g = Greeter.new("Alice")
puts g.greet
Defines a method greet inside a class using define_method that remembers the instance variable @name and uses it when called.
Execution Table
StepActionEvaluationResult
1Create Greeter instance with name 'Alice'Calls initialize with @name = 'Alice'Instance variable @name set to 'Alice'
2Inside initialize, define method :greet with define_methodMethod greet captures @name from closureMethod greet created and remembers @name = 'Alice'
3Call g.greetExecute greet method bodyReturns string 'Hello, Alice!'
4Print outputputs prints returned stringOutput: Hello, Alice!
5EndNo more codeExecution stops
💡 Execution stops after printing the greeting message.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
@namenil'Alice''Alice''Alice''Alice'
greet methodundefineddefined (captures @name='Alice')defined (captures @name='Alice')calleddefined (captures @name='Alice')
Key Moments - 2 Insights
Why does the greet method remember the value of @name even after initialize finishes?
Because define_method creates a closure that captures the surrounding context, including instance variables like @name, as shown in execution_table step 2.
What happens if we create another Greeter with a different name?
Each instance defines its own greet method capturing its own @name, so calling greet on different instances returns greetings with their respective names.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what does the greet method return?
A"Hello, Alice!"
B"Hello, nil!"
C"Hello, World!"
DAn error
💡 Hint
Check the 'Result' column at step 3 in execution_table.
At which step is the greet method created and remembers the @name variable?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' and 'Result' columns in execution_table for step 2.
If we create a new Greeter with name 'Bob', what will greet return when called?
A"Hello, Alice!"
B"Hello, nil!"
C"Hello, Bob!"
DAn error
💡 Hint
Refer to key_moments about multiple instances and variable capture.
Concept Snapshot
define_method(:name) do ... end creates a method dynamically.
This method captures variables from its surrounding context (closure).
When called, it uses those captured variables.
Useful for dynamic behavior tied to instance data.
Closures keep variables alive beyond method definition.
Full Transcript
This example shows how Ruby's define_method can create a method that remembers variables from its surrounding context, called closures. We create a Greeter class that sets an instance variable @name. Inside initialize, define_method creates a greet method that uses @name. When we call greet, it returns a greeting with the stored name. The execution table traces creating the instance, defining the method with closure, calling it, and printing the result. The variable tracker shows @name stays 'Alice' and greet method captures it. Key moments explain why the method remembers @name and what happens with multiple instances. The quiz tests understanding of method creation, closure capture, and output. This helps beginners see how define_method and closures work together in Ruby.