Object Initialization - Ruby


#1

https://www.codecademy.com/courses/learn-ruby/lessons/object-oriented-programming-i/exercises/instantiating-your-first-object?action=resume_content_item

Hello,

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


#2

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

steve = Person.new('Steve')

#3

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


#4

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


#5

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?


#6

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…

steve.method

or

steve.method(arg)

#7

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?


#8

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().


#9

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?


#10

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.


#11

Okay, thank you! I appreciate it.


#12

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