0
0
Rubyprogramming~5 mins

Define_method for dynamic methods in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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
end
Click to reveal answer
What argument does define_method take first?
AThe class name
BThe method body as a string
CThe method visibility
DThe method name as a symbol or string
Which of these is true about methods created with define_method?
AThey can only be private methods
BThey can access variables from the surrounding scope
CThey cannot take arguments
DThey must be defined outside classes
Why might you use define_method inside a loop?
ATo change method visibility
BTo delete existing methods
CTo create multiple methods with similar behavior but different names
DTo call methods automatically
What happens if you call define_method with a method name that already exists?
AIt overwrites the existing method
BIt raises an error
CIt ignores the new definition
DIt creates a method with a different name
Which Ruby feature allows define_method blocks to remember variables from outside?
AClosures
BInheritance
CModules
DSingleton methods
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.