Recall & Review
beginner
What does
define_method do in Ruby?<p><code>define_method</code> creates a new method dynamically at runtime. It lets you define a method with a given name and block of code inside a class or module.</p>Click to reveal answer
beginner
How do you use
define_method to create a method named greet that prints 'Hello'?define_method(:greet) do puts 'Hello' end
Click to reveal answer
intermediate
Why use
define_method instead of regular method definitions?It helps when you want to create many similar methods dynamically, or when method names depend on data available only at runtime.
Click to reveal answer
intermediate
Can
define_method access variables from the surrounding scope?Yes, the block passed to define_method can use variables from the surrounding scope because it is a closure.
Click to reveal answer
intermediate
What is a simple example of using
define_method to create multiple methods in a loop?[:one, :two, :three].each do |name|
define_method(name) do
puts "Method #{name} called"
end
endClick to reveal answer
What argument does
define_method take first?✗ Incorrect
define_method first takes the method name as a symbol or string, then a block defining the method body.
Which of these is true about methods created with
define_method?✗ Incorrect
Methods created with define_method can access variables from the surrounding scope because the block is a closure.
Why might you use
define_method inside a loop?✗ Incorrect
Using define_method inside a loop lets you create many methods with different names but similar code easily.
What happens if you call
define_method with a method name that already exists?✗ Incorrect
define_method will overwrite the existing method with the new definition.
Which Ruby feature allows
define_method blocks to remember variables from outside?✗ Incorrect
Closures let blocks remember variables from the surrounding scope, which define_method uses.
Explain how
define_method can be used to create methods dynamically in Ruby.Think about how you can create methods when you don't know their names before running the program.
You got /4 concepts.
Describe a scenario where using
define_method is better than writing methods normally.Imagine you want to create methods based on a list of names or actions.
You got /4 concepts.