Object Initialization - Ruby



I just have a question regarding objected-oriented programming. In the exercise I’ve provided the link to, when the class “Person” is invoked and some parameters are passed in, how does the class know to invoke the “initialize” method? Normally classes have several methods, without specifying which method is to be invoked, how does the class know which one to access to perform the desired task?

Thank you

The initialize method is immediately invoked on the parameters passed in to the new method.

steve = Person.new('Steve')

Yes, but how does the program know to use a specific method within the class “Person”?

That would be internal wiring of Ruby whereby the new method invokes the initialize method on the given class.

Okay, that makes sense. What if I had 2 or 3 other methods within my “Person” class, what would determine which method is invoked when a new Person object is instantiated?

None of the methods would be invoked upon instantiation unless they happen to be class methods invoked on a new instance during initialization. Take for instance an id attribute that is computed and assigned to each new instance so they are all unique. That’s a bit more than we are ready to grasp at this point so put this idea on the back burner for now.

The methods in a class are invoked manually on the instance…




That makes sense, thank you. So the reason the initialize method was invoked in the example I provided is because when creating my new object, I used the new keyword and then passed parameters, so the method with the corresponding number of arguments was invoked?

1 Like

The number of arguments is not a detemining factor. We might expect an exception to be raised if the argument count in the new call doesn’t correspond with the number of parameters of the initialze method, but that will take some testing.

I am not intimately familiar with the inner workings of Ruby so this answer is notably quite vague.

For now, let’s assume that new makes a call to initialize and passes the arguments along.

steve = Person.new

wrong number of arguments (given 0, expected 1)

Same applies to steve = Person.new().

Okay, thank you. What if there had been another method in the class that also took a string as an argument, how would Ruby decide which method is to be invoked?

1 Like

Ruby doesn’t decide anything. The new method is invoked which in turn invokes the initialize method. We the programmers decide the rest, such as what methods to include in the class, and when and how to invoke them. Ruby only tries to follow our directions.

Okay, thank you! I appreciate it.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.