Bird
Raised Fist0
Rubyprogramming~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the purpose of the initialize method in a Ruby class?
easy
A. It sets up initial values for a new object automatically.
B. It deletes an object from memory.
C. It prints the object details to the screen.
D. It defines a class method.

Solution

  1. Step 1: Understand the role of initialize

    The initialize method is called automatically when a new object is created.
  2. Step 2: Recognize what initialize does

    It sets starting values for the object's instance variables, preparing the object for use.
  3. Final Answer:

    It sets up initial values for a new object automatically. -> Option A
  4. Quick Check:

    initialize sets starting values [OK]
Hint: Remember: initialize runs when you create a new object [OK]
Common Mistakes:
  • Thinking initialize deletes objects
  • Confusing initialize with printing methods
  • Believing initialize defines class methods
2. Which of the following is the correct way to define an initialize method in Ruby?
easy
A. def initialize(name) @name = name end
B. def Initialize(name) @name = name end
C. initialize def(name) @name = name end
D. def init(name) @name = name end

Solution

  1. Step 1: Check method naming conventions

    Ruby requires the constructor method to be named exactly initialize in lowercase.
  2. Step 2: Verify method syntax

    def initialize(name) @name = name end correctly defines def initialize(name) and assigns the instance variable @name.
  3. Final Answer:

    def initialize(name)\n @name = name\nend -> Option A
  4. Quick Check:

    Method name must be initialize lowercase [OK]
Hint: Use lowercase 'initialize' exactly to define constructor [OK]
Common Mistakes:
  • Capitalizing 'Initialize' instead of 'initialize'
  • Using wrong method syntax order
  • Naming method 'init' instead of 'initialize'
3. What will be the output of this Ruby code?
class Person
  def initialize(name)
    @name = name
  end
  def greet
    "Hello, #{@name}!"
  end
end

p = Person.new("Alice")
puts p.greet
medium
A. Hello, @name!
B. Hello, Alice!
C. Hello, !
D. Error: undefined method greet

Solution

  1. Step 1: Understand object creation and initialization

    The Person.new("Alice") calls initialize with "Alice", setting @name to "Alice".
  2. Step 2: Check the greet method output

    The greet method returns "Hello, #{@name}!" which becomes "Hello, Alice!" when printed.
  3. Final Answer:

    Hello, Alice! -> Option B
  4. Quick Check:

    Instance variable set in initialize used in greet [OK]
Hint: Instance variables set in initialize are accessible in other methods [OK]
Common Mistakes:
  • Expecting '@name' to print literally
  • Forgetting to call greet method
  • Confusing instance variable scope
4. Identify the error in this Ruby class definition:
class Car
  def initialize(make, model)
    make = make
    model = model
  end
end

car = Car.new("Toyota", "Corolla")
puts car.make
medium
A. The initialize method should not have parameters.
B. The puts statement should be puts car.model
C. The class name should be lowercase.
D. Instance variables are not assigned; should use @make and @model.

Solution

  1. Step 1: Check variable assignment in initialize

    The code assigns local variables make = make and model = model, which do nothing to the object.
  2. Step 2: Correct usage of instance variables

    To store values in the object, it should assign @make = make and @model = model.
  3. Final Answer:

    Instance variables are not assigned; should use @make and @model. -> Option D
  4. Quick Check:

    Use @variable to store data in object [OK]
Hint: Use @ before variable to save it in the object [OK]
Common Mistakes:
  • Assigning to local variables instead of instance variables
  • Thinking parameters auto become instance variables
  • Wrong class naming conventions
5. You want to create a Ruby class Book that stores title and author when a new book is created. Which code correctly uses initialize to do this and allows reading these values later?
hard
A. class Book def initialize(title, author) @title = title @author = author end def title title end end
B. class Book def initialize(title, author) title = title author = author end end
C. class Book attr_reader :title, :author def initialize(title, author) @title = title @author = author end end
D. class Book def initialize(title, author) @title = title @author = author end def get_title @title end end

Solution

  1. Step 1: Check instance variable assignment

    Three options assign @title = title and @author = author correctly in initialize.
  2. Step 2: Verify how values are accessed

    class Book attr_reader :title, :author def initialize(title, author) @title = title @author = author end end uses attr_reader to create getter methods for both title and author, allowing easy access.
  3. Step 3: Identify issues in other options

    class Book def initialize(title, author) title = title author = author end end does not assign instance variables, so values are lost. class Book def initialize(title, author) @title = title @author = author end def title title end end's title method returns local variable title which is undefined. class Book def initialize(title, author) @title = title @author = author end def get_title @title end end only provides a getter for title, not author.
  4. Final Answer:

    class Book attr_reader :title, :author def initialize(title, author) @title = title @author = author end end -> Option C
  5. Quick Check:

    Use attr_reader with instance variables for easy access [OK]
Hint: Use attr_reader to read instance variables easily [OK]
Common Mistakes:
  • Not assigning instance variables in initialize
  • Returning undefined local variables in getter methods
  • Missing getter methods for instance variables
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard