Look at this Ruby class with an initialize method. What will be printed when we create a new object?
class Person def initialize(name) @name = name end def greet "Hello, #{@name}!" end end person = Person.new("Alice") puts person.greet
Remember, initialize sets instance variables when creating a new object.
The initialize method sets @name to "Alice". The greet method uses this variable to print "Hello, Alice!".
What will happen if we try to create a new object with an argument but the class has no initialize method?
class Car def start "Car started" end end car = Car.new("Toyota") puts car.start
If you pass arguments to new but no initialize accepts them, Ruby raises an error.
The default initialize takes no arguments. Passing "Toyota" causes an ArgumentError.
Find the error in this Ruby class and explain why it happens.
class Book def initialize(title) @title = title end def show_title "Title: #{@title}" end end book = Book.new("Ruby Guide") puts book.show_title
Check how instance variables are assigned and accessed in Ruby.
The code assigns to a local variable title inside initialize, not to an instance variable @title. The method show_title tries to use title which is undefined in that scope, causing a NameError.
Choose the best description of what the initialize method does in Ruby.
Think about what happens when you write ClassName.new.
The initialize method runs automatically during object creation to set up instance variables or other setup tasks.
Analyze this Ruby class with multiple parameters in initialize. What will be printed?
class Rectangle def initialize(width, height) @width = width @height = height end def area @width * @height end end rect = Rectangle.new(5, 3) puts rect.area
Multiply width and height stored in instance variables.
The initialize method sets @width to 5 and @height to 3. The area method returns 5 * 3 = 15.