0
0
Rubyprogramming~5 mins

Initialize method as constructor in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AIt sets up initial values when an object is created
BIt deletes an object
CIt prints output to the screen
DIt pauses the program
How do you call the initialize method directly?
ABy calling <code>init()</code>
BBy typing <code>initialize()</code>
CYou never call it directly; Ruby calls it when you use <code>.new</code>
DBy calling <code>constructor()</code>
What does @name represent inside the initialize method?
AAn instance variable that stores data for the object
BA local variable only inside the method
CA global variable
DA method name
What happens if you define initialize with parameters but call .new without arguments?
AThe program ignores the parameters
BRuby uses default values automatically
CThe object is created with nil values
DRuby raises an error because arguments are missing
Which keyword is used to create a new object that triggers initialize?
A.build
B.new
C.create
D.start
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.