0
0
Rubyprogramming~20 mins

Initialize method as constructor in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Initialize Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code with initialize method?

Look at this Ruby class with an initialize method. What will be printed when we create a new object?

Ruby
class Person
  def initialize(name)
    @name = name
  end

  def greet
    "Hello, #{@name}!"
  end
end

person = Person.new("Alice")
puts person.greet
AHello, !
BHello, @name!
CHello, Alice!
DError: undefined method `greet`
Attempts:
2 left
💡 Hint

Remember, initialize sets instance variables when creating a new object.

Predict Output
intermediate
2:00remaining
What happens if initialize method is missing?

What will happen if we try to create a new object with an argument but the class has no initialize method?

Ruby
class Car
  def start
    "Car started"
  end
end

car = Car.new("Toyota")
puts car.start
ACar started
BArgumentError: wrong number of arguments (given 1, expected 0)
CNoMethodError: undefined method `start`
Dnil
Attempts:
2 left
💡 Hint

If you pass arguments to new but no initialize accepts them, Ruby raises an error.

🔧 Debug
advanced
2:30remaining
Why does this initialize method cause an error?

Find the error in this Ruby class and explain why it happens.

Ruby
class Book
  def initialize(title)
    @title = title
  end

  def show_title
    "Title: #{@title}"
  end
end

book = Book.new("Ruby Guide")
puts book.show_title
ASyntaxError: unexpected local variable assignment
BPrints: Title: Ruby Guide
CPrints: Title:
DNameError: undefined local variable or method `title`
Attempts:
2 left
💡 Hint

Check how instance variables are assigned and accessed in Ruby.

🧠 Conceptual
advanced
1:30remaining
What is the role of the initialize method in Ruby classes?

Choose the best description of what the initialize method does in Ruby.

AIt is called automatically when a new object is created to set up initial values.
BIt defines a method that must be called manually after creating an object.
CIt is used to destroy objects and free memory.
DIt is a special method that runs only when the program ends.
Attempts:
2 left
💡 Hint

Think about what happens when you write ClassName.new.

Predict Output
expert
2:30remaining
What is the output of this Ruby code with multiple initialize parameters?

Analyze this Ruby class with multiple parameters in initialize. What will be printed?

Ruby
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
A15
B53
CError: wrong number of arguments (given 2, expected 1)
D0
Attempts:
2 left
💡 Hint

Multiply width and height stored in instance variables.