Challenge - 5 Problems
Ruby Define_Method Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of dynamic method using define_method
What is the output of this Ruby code that uses
define_method to create a dynamic method?Ruby
class Greeter def initialize(name) @name = name end define_method(:greet) do "Hello, #{@name}!" end end g = Greeter.new("Alice") puts g.greet
Attempts:
2 left
💡 Hint
Remember that
define_method creates an instance method that can access instance variables.✗ Incorrect
The
define_method block is evaluated in the context of the instance, so @name refers to the instance variable. Calling g.greet returns "Hello, Alice!".🧠 Conceptual
intermediate1:30remaining
Understanding scope in define_method blocks
Which statement about the scope of variables inside a
define_method block is true?Attempts:
2 left
💡 Hint
Think about where the block is executed when the dynamic method is called.
✗ Incorrect
The block passed to
define_method runs in the context of the instance, so it can access instance variables. However, it does not have access to local variables from the surrounding method where define_method was called.🔧 Debug
advanced2:00remaining
Why does this define_method code raise an error?
This Ruby code raises an error. What is the cause?
Ruby
class Calculator define_method(:add) do |a, b| a + b end end calc = Calculator.new puts calc.add(5)
Attempts:
2 left
💡 Hint
Check how many arguments the method expects versus how many are given.
✗ Incorrect
The dynamically defined method
add expects two arguments, but only one is given when calling calc.add(5). This causes an ArgumentError.📝 Syntax
advanced1:30remaining
Identify the syntax error in define_method usage
Which option contains a syntax error when using
define_method?Ruby
class Person define_method(:say_hello) do puts "Hello!" end end
Attempts:
2 left
💡 Hint
Check the block syntax used with
define_method.✗ Incorrect
Option A contains a syntax error:
define_method(:say_hello) do puts "Hello!" end used inline without block parameters (e.g. do ||) or newline after do fails to parse. do...end blocks require parameters or newline for body when not multiline. Use { ... } for inline blocks.🚀 Application
expert3:00remaining
Create dynamic getter methods with define_method
Given the following Ruby class, which option correctly uses
define_method to create getter methods for each attribute in ATTRIBUTES?Ruby
class Product ATTRIBUTES = [:name, :price, :stock] def initialize(name, price, stock) @name = name @price = price @stock = stock end # Define getter methods dynamically here end
Attempts:
2 left
💡 Hint
Use
instance_variable_get with the correct instance variable name string.✗ Incorrect
Option A correctly defines getter methods by calling
instance_variable_get with the instance variable name as a string, e.g., "@name". Other options either use the symbol directly or incorrect variable references.