0
0
Rubyprogramming~5 mins

Module_eval for dynamic behavior in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does module_eval do in Ruby?

module_eval runs a string or block of code inside the context of a module or class, allowing you to add or change methods dynamically.

Click to reveal answer
beginner
How can module_eval be used to add a method to a class?
<p>You pass a string defining the method to <code>module_eval</code>, and it adds that method to the class or module.</p><pre>MyClass.module_eval do
  def greet
    "Hello!"
  end
end</pre>
Click to reveal answer
intermediate
What is a practical use case for module_eval?

It helps when you want to create methods or change behavior based on data or conditions at runtime, like generating methods from a list of names.

Click to reveal answer
intermediate
What is the difference between module_eval and class_eval?

They are very similar; both evaluate code in the context of a module or class. class_eval is just an alias for module_eval when used on classes.

Click to reveal answer
advanced
Can module_eval access instance variables of the module or class?

Yes, inside the block or string passed to module_eval, you can access and modify instance variables of the module or class.

Click to reveal answer
What does module_eval primarily allow you to do?
ACompile Ruby code to machine code
BCreate a new module
CRun code inside a module or class context
DDelete methods from a class
Which of these is a correct way to add a method using module_eval?
AMyClass.module_eval { def hello; 'Hi'; end }
BMyClass.module_eval(:hello) { 'Hi' }
CMyClass.module_eval('hello')
DMyClass.module_eval(:def hello end)
What is a key benefit of using module_eval?
ADynamic method creation at runtime
BStatic code analysis
CFaster execution speed
DMemory optimization
Which is true about class_eval compared to module_eval?
A<code>class_eval</code> is only for classes, <code>module_eval</code> only for modules
B<code>class_eval</code> is an alias of <code>module_eval</code> for classes
C<code>class_eval</code> cannot add methods
D<code>module_eval</code> is deprecated
Can module_eval access instance variables of the module or class it is called on?
AOnly if passed as arguments
BNo, it only accesses class methods
COnly in Ruby versions before 2.0
DYes, it can access and modify them
Explain how module_eval can be used to add methods dynamically to a Ruby class.
Think about passing a block or string with method code.
You got /4 concepts.
    Describe the difference and similarity between module_eval and class_eval.
    Consider their usage on classes and modules.
    You got /3 concepts.