0
0
Rubyprogramming~20 mins

Class.new for dynamic class creation in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Dynamic Class Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
AHello from dynamic class!
BNoMethodError
CSyntaxError
Dnil
Attempts:
2 left
💡 Hint
Look at how the method greet is defined inside the Class.new block.
Predict Output
intermediate
2: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
ANoMethodError
BChild says hello
CParent says hi
DParent says hi and Child says hello
Attempts:
2 left
💡 Hint
Remember that super calls the method from the parent class.
🔧 Debug
advanced
2: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)
AArgumentError: wrong number of arguments (given 0, expected 1)
BSyntaxError: unexpected end-of-input
CNoMethodError: undefined method 'initialize'
Dnil
Attempts:
2 left
💡 Hint
Check how many arguments are passed to new versus initialize method parameters.
📝 Syntax
advanced
2: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'.
A
MyClass = Class.new do
  def self.info
    'Dynamic class'
  end
end
B
MyClass = Class.new do
  def info
    'Dynamic class'
  end
end

MyClass.info
C
MyClass = Class.new do
  class << self
    def info
      'Dynamic class'
    end
  end
end
D
MyClass = Class.new do
  def info()
    'Dynamic class'
  end
end

MyClass.info
Attempts:
2 left
💡 Hint
Class methods can be defined inside 'class << self' block or with 'def self.method'.
🚀 Application
expert
2: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
A1
B3
C6
D0
Attempts:
2 left
💡 Hint
Subtracting Object's methods from obj's methods leaves only methods defined in MyClass.