juniorRuby
What is the purpose of the 'initialize' method in Ruby classes?
Updated May 17, 2026
Short answer
The initialize method is the constructor for Ruby classes. It is automatically called whenever you call Class.new to instantiate an object.
Deep explanation
When Class.new is called, Ruby allocates memory for a new object instance and then internally invokes the initialize method on that instance, forwarding any parameters passed to new. It is used to set up the default state, bind initial instance variables, and enforce dependency injection requirements at initialization time.
Real-world example
Creating service objects or domain entities where specific attributes (like a database client or entity ID) must be supplied before any operations can take place.
Common mistakes
- Trying to explicitly call `object.initialize`. The `initialize` method is private by default, and calling it directly will raise a `NoMethodError`.
Follow-up questions
- Can you change the visibility of the initialize method?
- What method actually allocates the memory before initialize runs?