0
0
Rubyprogramming~10 mins

Initialize method as constructor 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 define a constructor method named initialize.

Ruby
class Person
  def [1](name)
    @name = name
  end
end
Drag options to blanks, or click blank then click option'
Aconstructor
Binit
Cinitialize
Dnew
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'init' or 'constructor' instead of 'initialize'.
Trying to name the method 'new' which is a class method, not the constructor.
2fill in blank
medium

Complete the code to create a new Person object with the name 'Alice'.

Ruby
person = Person.[1]('Alice')
Drag options to blanks, or click blank then click option'
Anew
Binitialize
Ccreate
Dbuild
Attempts:
3 left
💡 Hint
Common Mistakes
Calling 'initialize' directly instead of 'new'.
Using methods like 'create' or 'build' which are not standard Ruby constructors.
3fill in blank
hard

Fix the error in the initialize method to correctly assign the age parameter to an instance variable.

Ruby
class Person
  def initialize(age)
    [1] = age
  end
end
Drag options to blanks, or click blank then click option'
Athis.age
Bage
Cself.age
D@age
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning to a local variable instead of an instance variable.
Using 'self.age' which requires an accessor method.
4fill in blank
hard

Fill both blanks to define an initialize method that sets @name and @age from parameters.

Ruby
class Person
  def initialize([1], [2])
    @name = name
    @age = age
  end
end
Drag options to blanks, or click blank then click option'
Aname
Bage
Cname, age
Dfirst_name, years
Attempts:
3 left
💡 Hint
Common Mistakes
Using a single parameter with a comma inside it.
Using different parameter names that don't match the instance variables.
5fill in blank
hard

Fill all three blanks to create a Person class with initialize method and a method to display the name.

Ruby
class Person
  def [1](name)
    @name = name
  end

  def [2]
    puts "Name: [3]"
  end
end
Drag options to blanks, or click blank then click option'
Ainitialize
Bdisplay_name
C@name
Dshow
Attempts:
3 left
💡 Hint
Common Mistakes
Naming the constructor something other than 'initialize'.
Using a wrong variable name inside the puts statement.
Using method names that don't match the instruction.