Bird
Raised Fist0
Rubyprogramming~20 mins

Define_method with closures in Ruby - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Define_method Closure Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of define_method capturing variable
What is the output of this Ruby code?
class Greeter
  def initialize(name)
    @name = name
  end

  def create_greeting
    define_method(:greet) do
      "Hello, #{@name}!"
    end
  end
end

g = Greeter.new("Alice")
g.create_greeting
g.greet
Ruby
class Greeter
  def initialize(name)
    @name = name
  end

  def create_greeting
    define_method(:greet) do
      "Hello, #{@name}!"
    end
  end
end

g = Greeter.new("Alice")
g.create_greeting
g.greet
ANoMethodError: undefined method `greet' for #<Greeter:0x000...>
B"Hello, !"
C"Hello, Alice!"
DSyntaxError
Attempts:
2 left
💡 Hint
Think about how define_method captures instance variables in closures.
❓ Predict Output
intermediate
2:00remaining
Closure behavior with loop variable in define_method
What is the output of this Ruby code?
class Counter
  def initialize
    @methods = []
    3.times do |i|
      define_singleton_method("count_#{i}") do
        i
      end
    end
  end
end

c = Counter.new
[c.count_0, c.count_1, c.count_2]
Ruby
class Counter
  def initialize
    @methods = []
    3.times do |i|
      define_singleton_method("count_#{i}") do
        i
      end
    end
  end
end

c = Counter.new
[c.count_0, c.count_1, c.count_2]
A[0, 1, 2]
B[2, 2, 2]
C[nil, nil, nil]
DNoMethodError
Attempts:
2 left
💡 Hint
Each define_singleton_method captures the current value of i during the loop.
🔧 Debug
advanced
2:00remaining
Why does this define_method not capture the variable as expected?
Consider this Ruby code:
class Example
  def create_methods
    names = ["foo", "bar"]
    names.each do |name|
      define_method(name) do
        name
      end
    end
  end
end

ex = Example.new
ex.create_methods
puts ex.foo
puts ex.bar

What is the output and why?
Ruby
class Example
  def create_methods
    names = ["foo", "bar"]
    names.each do |name|
      define_method(name) do
        name
      end
    end
  end
end

ex = Example.new
ex.create_methods
puts ex.foo
puts ex.bar
Afoo\nbar
Bfoo\nfoo
Cbar\nbar
DNameError
Attempts:
2 left
💡 Hint
Think about how the block variable 'name' is captured in the closure.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in define_method usage
Which option contains a syntax error when defining a method with define_method?
class Test
  def setup
    define_method(:hello) do
      puts "Hello"
    end
  end
end
Ruby
class Test
  def setup
    define_method(:hello) do
      puts "Hello"
    end
  end
end
Adefine_method(:hello) do puts "Hello" end
Bdefine_method(:hello) { puts "Hello" }
C
define_method(:hello) do
  puts "Hello"
end
Ddefine_method(:hello) puts "Hello" end
Attempts:
2 left
💡 Hint
Check the block syntax carefully.
🚀 Application
expert
3:00remaining
Using define_method with closures to create dynamic attribute methods
You want to create a Ruby class that dynamically defines getter methods for a list of attributes using define_method and closures. Which option correctly defines these methods so that each getter returns the correct attribute value?
class DynamicAttrs
  def initialize(attrs)
    @attrs = attrs
    # define getters here
  end
end

obj = DynamicAttrs.new({name: "Bob", age: 30})
obj.name # => "Bob"
obj.age  # => 30
Ruby
class DynamicAttrs
  def initialize(attrs)
    @attrs = attrs
    # define getters here
  end
end

obj = DynamicAttrs.new({name: "Bob", age: 30})
obj.name
obj.age
A
def initialize(attrs)
  @attrs = attrs
  attrs.each do |key, value|
    define_singleton_method(key) { value }
  end
end
B
def initialize(attrs)
  @attrs = attrs
  attrs.each do |key, value|
    define_singleton_method(key) { @attrs[key] }
  end
end
C
def initialize(attrs)
  @attrs = attrs
  attrs.each do |key, value|
    define_method(key) { @attrs[key] }
  end
end
D
def initialize(attrs)
  @attrs = attrs
  attrs.each do |key, value|
    define_method(key) { value }
  end
end
Attempts:
2 left
💡 Hint
Consider where the methods are defined and how closures capture variables.

Practice

(1/5)
1. What does define_method do in Ruby?
easy
A. Defines a class variable
B. Deletes an existing method
C. Calls a method immediately
D. Creates a method dynamically using a block

Solution

  1. Step 1: Understand the purpose of define_method

    define_method is used to create methods dynamically at runtime using a block of code.
  2. Step 2: Compare with other options

    Options B, C, and D describe different actions unrelated to define_method.
  3. Final Answer:

    Creates a method dynamically using a block -> Option D
  4. Quick Check:

    define_method creates methods dynamically [OK]
Hint: Remember: define_method builds methods with blocks [OK]
Common Mistakes:
  • Thinking define_method calls methods
  • Confusing define_method with deleting methods
  • Assuming it defines variables
2. Which of the following is the correct syntax to define a method named greet using define_method that returns "Hello"?
easy
A. def define_method(:greet) "Hello" end
B. define_method greet { return "Hello" }
C. define_method(:greet) { "Hello" }
D. define_method(:greet, "Hello")

Solution

  1. Step 1: Recall correct define_method syntax

    The correct syntax uses a symbol for the method name and a block: define_method(:name) { ... }.
  2. Step 2: Check each option

    def define_method(:greet) "Hello" end uses def incorrectly. define_method greet { return "Hello" } lacks symbol (greet undefined). define_method(:greet, "Hello") passes string instead of block. B matches correct syntax.
  3. Final Answer:

    define_method(:greet) { "Hello" } -> Option C
  4. Quick Check:

    Correct syntax uses symbol and block [OK]
Hint: Use symbol and block for define_method syntax [OK]
Common Mistakes:
  • Using method name without symbol
  • Incorrect block syntax
  • Using def inside define_method
3. What will be the output of this Ruby code?
class Person
  def initialize(name)
    @name = name
    self.class.define_method(:greet) { "Hello, #{@name}!" }
  end
end

p = Person.new("Alice")
puts p.greet
medium
A. Hello, Alice!
B. Hello, !
C. NoMethodError
D. SyntaxError

Solution

  1. Step 1: Understand closure and instance variable scope

    The block passed to define_method defines the method body. However, the string interpolation "Hello, #{@name}!" is evaluated immediately when define_method is called, not when the method is invoked. At that time, @name is nil because the block is defined in the class context, not the instance context.
  2. Step 2: Predict output

    Therefore, the method greet returns the string with @name interpolated as nil, resulting in "Hello, !".
  3. Final Answer:

    Hello, ! -> Option B
  4. Quick Check:

    String interpolation in define_method block evaluated immediately [OK]
Hint: String interpolation in define_method block is evaluated immediately [OK]
Common Mistakes:
  • Thinking @name is dynamically resolved inside the block
  • Expecting 'Hello, Alice!' due to misunderstanding of closure
  • Confusing instance and class scope
4. Identify the error in this code snippet:
class Calculator
  def initialize(x)
    @x = x
    self.class.define_method(:square) { @x * @x }
  end
end

calc = Calculator.new(4)
puts calc.square
medium
A. No error, outputs 16
B. Syntax error in define_method block
C. The block does not capture @x correctly, causing nil * nil error
D. The method square is not defined for instances

Solution

  1. Step 1: Analyze where define_method is called

    define_method on self.class defines an instance method square. The block executes in instance context.
  2. Step 2: Understand closure and instance variable scope

    @x resolved on instance: 4 * 4 = 16. No capture issue, no error.
  3. Final Answer:

    No error, outputs 16 -> Option A
  4. Quick Check:

    Instance vars work in class-level define_method [OK]
Hint: Instance vars work in class-level define_method blocks [OK]
Common Mistakes:
  • Thinking method undefined for instances
  • Expecting syntax error
  • Believing nil * nil error from poor capture
5. How can you fix this code so that each instance of Person has a greet method that correctly uses its own @name?
class Person
  def initialize(name)
    @name = name
    self.class.define_method(:greet) { "Hello, #{@name}!" }
  end
end

p1 = Person.new("Bob")
p2 = Person.new("Carol")
puts p1.greet
puts p2.greet
hard
A. Define greet method inside initialize using define_singleton_method
B. Use self.class.define_method but pass @name as parameter
C. Move @name to a class variable
D. Use def greet; "Hello, #{@name}!"; end inside initialize

Solution

  1. Step 1: Understand the problem with class-level define_method

    Class-level define_method in initialize redefines a shared instance method each time (inefficient, problematic for local var closures). Instance vars work via dynamic lookup.
  2. Step 2: Use define_singleton_method to define method per instance

    define_singleton_method defines on the instance's singleton class, giving each its own greet accessing own @name.
  3. Final Answer:

    Define greet method inside initialize using define_singleton_method -> Option A
  4. Quick Check:

    Use define_singleton_method for per-instance closures [OK]
Hint: Use define_singleton_method for instance-specific methods [OK]
Common Mistakes:
  • Trying to pass instance vars as parameters to class method
  • Using class variables instead of instance variables
  • Defining method with def inside initialize incorrectly
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