Challenge - 5 Problems
Dynamic Class Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code using Class.new?
Consider this Ruby code that creates a class dynamically and uses it:
Ruby
MyClass = Class.new do def greet "Hello from dynamic class!" end end obj = MyClass.new puts obj.greet
Attempts:
2 left
💡 Hint
Look at how the method greet is defined inside the Class.new block.
✗ Incorrect
The Class.new block defines a method greet. When we create an instance and call greet, it returns the string.
❓ Predict Output
intermediate2:00remaining
What does this code print when using Class.new with inheritance?
This Ruby code creates a subclass dynamically. What is printed?
Ruby
class Parent def message "Parent says hi" end end Child = Class.new(Parent) do def message super + " and Child says hello" end end puts Child.new.message
Attempts:
2 left
💡 Hint
Remember that super calls the method from the parent class.
✗ Incorrect
The Child class overrides message but calls super to get parent's message, then adds its own text.
🔧 Debug
advanced2:00remaining
Why does this dynamic class creation code raise an error?
This Ruby code tries to create a class dynamically but raises an error. Identify the cause.
Ruby
MyClass = Class.new do def initialize(name) @name = name end end obj = MyClass.new puts obj.instance_variable_get(:@name)
Attempts:
2 left
💡 Hint
Check how many arguments are passed to new versus initialize method parameters.
✗ Incorrect
The initialize method expects one argument, but new is called without arguments, causing ArgumentError.
📝 Syntax
advanced2:00remaining
Which option correctly defines a dynamic class with a class method using Class.new?
Select the Ruby code that correctly creates a class with a class method 'info' returning 'Dynamic class'.
Attempts:
2 left
💡 Hint
Class methods can be defined inside 'class << self' block or with 'def self.method'.
✗ Incorrect
Options A and C correctly define a class method (A using `def self.info`, C using `class << self`). Options B and D define an instance method but call it on the class, causing NoMethodError.
🚀 Application
expert2:00remaining
How many methods does this dynamically created class have?
Given this Ruby code, how many methods does the class MyClass respond to (excluding inherited methods)?
Ruby
MyClass = Class.new do def a 1 end def b 2 end def c 3 end end obj = MyClass.new methods = obj.methods - Object.new.methods puts methods.size
Attempts:
2 left
💡 Hint
Subtracting Object's methods from obj's methods leaves only methods defined in MyClass.
✗ Incorrect
The class defines three instance methods: a, b, and c. Subtracting inherited methods leaves these three.