Bird
Raised Fist0
Rubyprogramming~20 mins

Module_eval for dynamic behavior in Ruby - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Module_eval Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Ruby code using module_eval?

Consider this Ruby code that uses module_eval to add a method dynamically. What will it print?

Ruby
module Greeter
  module_eval do
    def greet
      "Hello from module_eval!"
    end
  end
end

class Person
  include Greeter
end

puts Person.new.greet
ARuntimeError: wrong number of arguments (given 0, expected 1)
BNoMethodError: undefined method `greet' for #<Person:0x000...>
CHello from module_eval!
DSyntaxError: (eval):2: syntax error, unexpected keyword_def
Attempts:
2 left
💡 Hint

Think about how module_eval adds methods to the module's instance methods.

❓ Predict Output
intermediate
2:00remaining
What error does this code raise when using module_eval incorrectly?

What error will this Ruby code raise?

Ruby
module M
  module_eval "def hello; 'Hi'; end"
  module_eval "def hello; 'Hi'"
end
ASyntaxError: (eval):2: syntax error, unexpected end-of-input, expecting `end`
BNoMethodError: undefined method `hello' for M:Module
CRuntimeError: can't redefine method
DNameError: undefined local variable or method `hello'
Attempts:
2 left
💡 Hint

Check the string passed to module_eval for proper method definition syntax.

🔧 Debug
advanced
2:00remaining
Why does this dynamically added method not work as expected?

Look at this Ruby code using module_eval. Why does calling obj.dynamic_method raise an error?

Ruby
module M
  module_eval do
    def dynamic_method
      'Dynamic!'
    end
  end
end

obj = Object.new
obj.extend(M)
puts obj.dynamic_method
ATypeError because <code>obj</code> is not a class
BSyntaxError due to incorrect use of module_eval block
CRuntimeError because <code>extend</code> cannot be used with modules modified by module_eval
DNoMethodError because <code>dynamic_method</code> is an instance method of M, but <code>obj</code> does not have it as a singleton method
Attempts:
2 left
💡 Hint

Think about how extend works and what methods it adds to an object.

📝 Syntax
advanced
2:00remaining
Which option correctly uses module_eval to define a class method?

Which code snippet correctly defines a class method info inside module M using module_eval?

A
module M
  module_eval do
    def self.info
      'Class method'
    end
  end
end
B
module M
  module_eval do
    def self.info
      'Class method'
    end
  end
end

class C
  extend M
end

puts C.info
C
module M
  module_eval do
    def info
      'Class method'
    end
  end
end

class &lt;&lt; self
  include M
end
D
module M
  module_eval "def self.info; 'Class method'; end"
end
Attempts:
2 left
💡 Hint

Remember that def self.method inside a module defines a method on the module object, not on classes including it.

🚀 Application
expert
3:00remaining
How to dynamically add multiple methods with module_eval from a hash?

You want to add multiple instance methods to a module dynamically using module_eval and a hash of method names and return values. Which code correctly does this?

Ruby
methods = { greet: 'Hello', farewell: 'Goodbye' }

module M
  # Add methods here
end

class Person
  include M
end

p = Person.new
puts p.greet
puts p.farewell
A
methods.each do |name, val|
  M.module_eval "def #{name}; '#{val}'; end"
end
B
methods.each do |name, val|
  M.module_eval do
    define_method(name) { val }
  end
end
C
methods.each do |name, val|
  M.module_eval do
    def name
      val
    end
  end
end
D
methods.each do |name, val|
  M.module_eval "define_method(:#{name}) { '#{val}' }"
end
Attempts:
2 left
💡 Hint

Think about how module_eval executes strings as code and how to interpolate method names and values correctly.

Practice

(1/5)
1.

What does module_eval do in Ruby?

easy
A. It converts a module into a class.
B. It deletes all methods from a module.
C. It creates a new module with fixed methods.
D. It allows adding or changing methods inside a module dynamically.

Solution

  1. Step 1: Understand the purpose of module_eval

    module_eval lets you run code inside a module's context, allowing you to add or change methods dynamically.

  2. Step 2: Compare options with the definition

    Only "It allows adding or changing methods inside a module dynamically." correctly describes this dynamic behavior. Other options describe unrelated actions.

  3. Final Answer:

    It allows adding or changing methods inside a module dynamically. -> Option D
  4. Quick Check:

    module_eval adds or changes methods = A [OK]
Hint: Remember: module_eval changes module methods at runtime [OK]
Common Mistakes:
  • Thinking module_eval deletes methods
  • Confusing module_eval with module creation
  • Assuming module_eval converts modules to classes
2.

Which of the following is the correct syntax to define a method greet inside a module Mod using module_eval?

module Mod
  # Your code here
end
easy
A. Mod.module_eval { def greet; 'Hi'; end }
B. Mod.module_eval def greet; 'Hi'; end
C. Mod.module_eval('def greet; 'Hi'; end')
D. Mod.module_eval :def greet; 'Hi'; end

Solution

  1. Step 1: Recall correct module_eval syntax

    You can pass a block to module_eval with method definitions inside curly braces.

  2. Step 2: Check each option's syntax

    Mod.module_eval { def greet; 'Hi'; end } uses a block correctly. Mod.module_eval def greet; 'Hi'; end misses braces. Mod.module_eval('def greet; 'Hi'; end') has mismatched quotes (inner single quote breaks the outer single-quoted string), causing syntax error. Mod.module_eval :def greet; 'Hi'; end uses invalid symbol syntax.

  3. Final Answer:

    Mod.module_eval { def greet; 'Hi'; end } -> Option A
  4. Quick Check:

    Block syntax with braces is correct = A [OK]
Hint: Use braces {} to pass a block to module_eval [OK]
Common Mistakes:
  • Omitting braces for block
  • Using invalid symbol syntax
  • Confusing string and block syntax
3.

What will be the output of the following Ruby code?

module M
  module_eval do
    def hello
      'Hello from M'
    end
  end
end

class C
  include M
end

puts C.new.hello
medium
A. Hello from M
B. NoMethodError
C. SyntaxError
D. nil

Solution

  1. Step 1: Understand method definition inside module_eval

    The method hello is defined inside module M using module_eval, so it becomes an instance method of M.
  2. Step 2: Check class inclusion and method call

    Class C includes M, so instances of C have hello method. Calling C.new.hello returns 'Hello from M'.
  3. Final Answer:

    Hello from M -> Option A
  4. Quick Check:

    module_eval defines method, include makes it accessible = D [OK]
Hint: module_eval defines methods accessible after include [OK]
Common Mistakes:
  • Assuming method is not defined
  • Confusing module_eval with class_eval
  • Expecting syntax error from block
4.

Identify the error in the following code snippet:

module M
  module_eval 'def greet; puts "Hi" end'
end

class C
  include M
end

C.new.greet
medium
A. The method greet is defined but calling it prints nothing.
B. No error; code runs and prints 'Hi'.
C. Syntax error due to missing semicolon in module_eval string.
D. NoMethodError because greet is not defined as an instance method.

Solution

  1. Step 1: Analyze module_eval string syntax

    The string passed to module_eval defines method greet correctly with a semicolon separating statements.
  2. Step 2: Check method availability and call

    Class C includes M, so greet is available to instances. Calling C.new.greet prints 'Hi'.
  3. Final Answer:

    No error; code runs and prints 'Hi'. -> Option B
  4. Quick Check:

    module_eval string defines method correctly = C [OK]
Hint: Check string syntax carefully; semicolon separates statements [OK]
Common Mistakes:
  • Thinking semicolon is missing
  • Assuming greet is not instance method
  • Expecting runtime error from string eval
5.

You want to dynamically add multiple methods foo and bar to a module Mod using module_eval. Which approach correctly adds both methods so they can be used by classes including Mod?

hard
A. Mod.module_eval do def self.foo; 'foo'; end end Mod.module_eval do def self.bar; 'bar'; end end
B. All of the above
C. Mod.module_eval do def foo; 'foo'; end def bar; 'bar'; end end
D. Mod.module_eval('def self.foo; "foo"; end') Mod.module_eval('def self.bar; "bar"; end')

Solution

  1. Step 1: Understand multiple method definitions with module_eval

    You can define multiple methods in one block or multiple times with separate calls to module_eval. Both ways add instance methods to the module.
  2. Step 2: Evaluate each option

    Mod.module_eval do def foo; 'foo'; end def bar; 'bar'; end end defines both as instance methods (no self.) in one block, correct. All of the above "All of the above" is incorrect. Mod.module_eval do def self.foo; 'foo'; end end Mod.module_eval do def self.bar; 'bar'; end end uses separate blocks but def self. adds singleton methods to Mod, not instance methods. Mod.module_eval('def self.foo; "foo"; end') Mod.module_eval('def self.bar; "bar"; end') uses strings with def self., same issue - not accessible after include.
  3. Final Answer:

    Mod.module_eval do def foo; 'foo'; end def bar; 'bar'; end end -> Option C
  4. Quick Check:

    Block with plain def (no self) adds instance methods = A [OK]
Hint: module_eval block with plain def defines instance methods [OK]
Common Mistakes:
  • Thinking only one method per module_eval is allowed
  • Confusing string and block syntax
  • Using self.def for instance methods (makes singletons)
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