Recall & Review
beginner
What is the purpose of the
initialize method in Ruby?The
initialize method is a special method in Ruby that acts as a constructor. It runs automatically when a new object is created, setting up initial values or state for that object.Click to reveal answer
beginner
How do you define an
initialize method inside a Ruby class?You define it like any other method but with the name <code>initialize</code>. It usually takes parameters to set up the object's initial state. Example:<br><pre>class Person
def initialize(name)
@name = name
end
end</pre>Click to reveal answer
beginner
What does the
@ symbol mean in @name = name inside initialize?The
@ symbol creates an instance variable. It stores data inside the object so it can be used later by other methods in the same object.Click to reveal answer
beginner
What happens if you create a new object without defining an
initialize method?Ruby uses a default constructor that does nothing. The object is created but no initial setup or variables are assigned automatically.
Click to reveal answer
beginner
Can the
initialize method take multiple parameters? How?Yes, it can take as many parameters as needed, separated by commas. Example:<br>
def initialize(name, age) @name = name @age = age end
Click to reveal answer
What is the role of the
initialize method in Ruby?✗ Incorrect
The
initialize method runs automatically when a new object is created to set up initial values.How do you call the
initialize method directly?✗ Incorrect
Ruby automatically calls
initialize when you create a new object with .new.What does
@name represent inside the initialize method?✗ Incorrect
@name is an instance variable that belongs to the object and keeps data accessible to other methods.What happens if you define
initialize with parameters but call .new without arguments?✗ Incorrect
If parameters are required in
initialize, you must provide them when calling .new, or Ruby raises an error.Which keyword is used to create a new object that triggers
initialize?✗ Incorrect
The
.new method creates a new object and automatically calls initialize.Explain how the
initialize method works as a constructor in Ruby and why it is useful.Think about what happens when you create a new object with .new.
You got /4 concepts.
Describe how you would define an
initialize method that takes two parameters and stores them in instance variables.Remember the format: def initialize(param1, param2)
You got /4 concepts.