Bird
Raised Fist0
Rubyprogramming~10 mins

Define_method for dynamic methods in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Define_method for dynamic methods
Start
↓
Call define_method with name and block
↓
Ruby creates method dynamically
↓
Method can be called like normal
↓
Method executes block code
↓
End
This flow shows how Ruby's define_method creates a method dynamically and then allows calling it like a normal method.
Execution Sample
Ruby
class Greeter
  define_method(:hello) do |name|
    "Hello, #{name}!"
  end
end

puts Greeter.new.hello("Alice")
This code defines a method 'hello' dynamically that greets a person by name, then calls it.
Execution Table
StepActionEvaluationResult
1Call define_method(:hello) with blockMethod 'hello' is created dynamicallyMethod 'hello' added to Greeter
2Create Greeter instanceInstance created#<Greeter:0x000...>
3Call hello("Alice") on instanceBlock runs with name='Alice'"Hello, Alice!" returned
4puts prints returned stringOutput to consoleHello, Alice!
💡 Method call completed and output printed
Variable Tracker
VariableStartAfter define_methodAfter instance creationAfter method call
hello (method)undefineddefined as dynamic methodavailable on instanceexecutes block with argument
name (block param)undefinedundefinedundefined"Alice" during method call
Key Moments - 2 Insights
Why can we call 'hello' on the instance even though it was not defined with 'def'?
Because define_method dynamically creates the method and adds it to the class, making it callable like any normal method (see execution_table step 1 and 3).
What is the role of the block passed to define_method?
The block contains the code that runs when the dynamic method is called. It can take parameters and return values (see execution_table step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of calling hello("Alice")?
Anil returned
BMethod not found error
C"Hello, Alice!" returned
D"hello" string returned
💡 Hint
Check execution_table row 3 for the method call result
At which step is the method 'hello' added to the Greeter class?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
See execution_table row 1 where define_method is called
If we change the block to return "Hi, #{name}", what changes in the execution_table output?
AOutput changes to "Hi, Alice"
BMethod creation fails
CNo change in output
DError at method call
💡 Hint
Output depends on the block code executed in step 3
Concept Snapshot
define_method(:name) { |params| ... } creates a method dynamically.
The method can be called like a normal method.
The block defines the method body.
Useful for dynamic or metaprogramming tasks.
Allows passing parameters and returning values.
Full Transcript
This example shows how Ruby's define_method creates a method dynamically inside a class. The method 'hello' is defined with a block that takes a name and returns a greeting string. When we create an instance of Greeter and call hello with 'Alice', the block runs and returns 'Hello, Alice!'. The method behaves like any normal method even though it was created dynamically. This is useful when you want to create methods on the fly based on conditions or data.

Practice

(1/5)
1. What does define_method do in Ruby?
easy
A. Creates a method dynamically during program execution
B. Deletes an existing method from a class
C. Calls a method with given arguments
D. Defines a constant value in a class

Solution

  1. Step 1: Understand the purpose of define_method

    define_method allows creating methods while the program runs, not just when writing code.
  2. Step 2: Compare options with define_method behavior

    Only Creates a method dynamically during program execution correctly describes dynamic method creation. Other options describe unrelated actions.
  3. Final Answer:

    Creates a method dynamically during program execution -> Option A
  4. Quick Check:

    define_method = dynamic method creation [OK]
Hint: define_method creates methods while program runs [OK]
Common Mistakes:
  • Thinking define_method deletes methods
  • Confusing define_method with method calls
  • Assuming define_method defines constants
2. Which of the following is the correct syntax to define a method named greet dynamically inside a class using define_method?
easy
A. define_method('greet') { puts 'Hello' }
B. define_method :greet puts 'Hello' end
C. def define_method :greet puts 'Hello' end
D. define_method greet puts 'Hello'

Solution

  1. Step 1: Recall correct define_method syntax

    The method name can be a symbol or string, and the method body is given as a block.
  2. Step 2: Check each option for syntax correctness

    define_method('greet') { puts 'Hello' } uses parentheses and a block correctly. define_method :greet do puts 'Hello' end misses parentheses and block braces, causing syntax error. Options C and D have invalid syntax.
  3. Final Answer:

    define_method('greet') { puts 'Hello' } -> Option A
  4. Quick Check:

    define_method syntax = method name + block [OK]
Hint: Use parentheses and block for define_method syntax [OK]
Common Mistakes:
  • Omitting parentheses around method name
  • Not using a block for method body
  • Writing def inside define_method incorrectly
3. What will be the output of this Ruby code?
class Person
  [:walk, :run].each do |action|
    define_method(action) { puts "I can #{action}" }
  end
end

p = Person.new
p.walk
p.run
medium
A. I can run I can run
B. I can walk I can run
C. NoMethodError for walk
D. SyntaxError

Solution

  1. Step 1: Understand the loop and define_method usage

    The code loops over [:walk, :run] using each do |action| and defines two methods dynamically. Ruby blocks capture the loop variable action by value for each iteration, so each method captures its own action value.
  2. Step 2: Trace method calls on instance

    p.walk prints "I can walk" and p.run prints "I can run" as expected.
  3. Final Answer:

    I can walk I can run -> Option B
  4. Quick Check:

    Blocks capture loop variable per iteration [OK]
Hint: Blocks in Ruby loops capture loop variable per iteration [OK]
Common Mistakes:
  • Expecting same output for both methods (confuses closure capture)
  • Thinking methods are not defined
  • Confusing syntax with errors
4. Identify the error in this code snippet:
class Calculator
  [:add, :subtract].each do |op|
    define_method(op) do |a, b|
      if op == :add
        a + b
      else
        a - b
      end
    end
  end
end

calc = Calculator.new
puts calc.add(5, 3)
puts calc.subtract(5, 3)
medium
A. Wrong number of arguments passed to methods
B. Missing parentheses in method calls
C. The variable op inside the block always refers to the last symbol
D. Syntax error in define_method block

Solution

  1. Step 1: Understand variable capture in blocks

    The block uses op inside the method body, but op is from the outer loop and will be the last value (:subtract) when methods run.
  2. Step 2: Explain effect on method behavior

    Both methods will behave as if op == :subtract, so add will subtract incorrectly.
  3. Final Answer:

    The variable op inside the block always refers to the last symbol -> Option C
  4. Quick Check:

    Block variable capture causes wrong method behavior [OK]
Hint: Block variables may capture last loop value, causing bugs [OK]
Common Mistakes:
  • Assuming op is unique per method
  • Ignoring variable capture in closures
  • Thinking syntax is wrong
5. How can you fix the following code so that each dynamically defined method behaves correctly?
class Calculator
  [:add, :subtract].each do |op|
    define_method(op) do |a, b|
      if op == :add
        a + b
      else
        a - b
      end
    end
  end
end
hard
A. Pass op as a method argument
B. Replace define_method with def keyword
C. Remove the if-else and always return a + b
D. Use a local variable inside the loop to capture op value before define_method

Solution

  1. Step 1: Understand variable capture problem

    The variable op is shared in the loop and captured by the block, causing all methods to use the last value.
  2. Step 2: Fix by assigning op to a local variable inside the loop

    Assign current_op = op inside the loop, then use current_op inside define_method block to capture correct value.
  3. Final Answer:

    Use a local variable inside the loop to capture op value before define_method -> Option D
  4. Quick Check:

    Local variable capture fixes closure bug [OK]
Hint: Assign loop variable to local var before define_method [OK]
Common Mistakes:
  • Trying to pass op as method argument (won't fix closure)
  • Replacing define_method with def (loses dynamic behavior)
  • Ignoring the variable capture issue
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard