0
0
Rubyprogramming~10 mins

Class.new for dynamic class creation in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a new class dynamically using Class.new.

Ruby
MyClass = [1] do
  def greet
    'Hello!'
  end
end
Drag options to blanks, or click blank then click option'
AClass.new
Bclass.new
CNewClass
Dclass.New
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase 'class.new' instead of 'Class.new'.
Trying to use 'NewClass' as a method.
Using dot notation incorrectly like 'class.New'.
2fill in blank
medium

Complete the code to create an instance of the dynamically created class.

Ruby
obj = MyClass.[1]
Drag options to blanks, or click blank then click option'
Amake
Bcreate
Cnew
Dbuild
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'create' or 'build' which are not Ruby methods for instantiation.
Forgetting to call a method and just writing 'MyClass'.
3fill in blank
hard

Fix the error in the code to define a method inside the dynamically created class.

Ruby
MyClass = Class.new do
  def [1]
    'Hi there'
  end
end
Drag options to blanks, or click blank then click option'
Asay_hello
BsayHello
CSayHello
Dsay-hello
Attempts:
3 left
💡 Hint
Common Mistakes
Using camelCase like 'sayHello' which is not Ruby style.
Using capitalized method names which are constants.
Using hyphens which are invalid in method names.
4fill in blank
hard

Fill both blanks to create a dynamic class with an initialize method that sets a name attribute.

Ruby
Person = Class.new do
  def [1](name)
    @[2] = name
  end
end
Drag options to blanks, or click blank then click option'
Ainitialize
Bname
Cage
Dinit
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'init' instead of 'initialize'.
Using a wrong instance variable name like '@age' when parameter is 'name'.
5fill in blank
hard

Fill all three blanks to create a dynamic class with an attribute reader and a method that returns a greeting with the name.

Ruby
User = Class.new do
  attr_reader :[1]

  def initialize([2])
    @[3] = [2]
  end

  def greet
    "Hello, #{@[1]!"
  end
end
Drag options to blanks, or click blank then click option'
Aname
Busername
Duser
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing different names for attribute reader and instance variables.
Using undefined variables in the greet method.