In Ruby, what is the difference between putting code in an initialize()
method rather than directly in the class body? Both appear to be executed when calling MyClass.new
.
Clearly, initialize()
can accept parameters, but is that the only difference?
class MyClass puts 'Hello' def initialize(params) puts 'World' end end
The initialize method is useful when we want to initialize some class variables at the time of object creation. The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object.
new , the class will create a new instance of itself. It will then, internally, call the method initialize on the new object. Doing so it will simply pass all the arguments that you passed to new on to the method initialize .
An object instance is created from a class through the process called instantiation. In Ruby this takes place through the Class method new . Example: anObject = MyClass. new(parameters)
using Class. new declares an anonymous new class on the fly: Creates a new anonymous (unnamed) class with the given superclass (or Object if no parameter is given). You can give a class a name by assigning the class object to a constant.
Try to create two instances of MyClass
a = MyClass.new b = MyClass.new
to see the difference:
Hello
World
World
Code in the class body execute only once - when ruby loads the file. initialize() executes every time you create a new instance of your class.
Well, initialize
gets called by new
, whereas the class body gets evaluated on class definition/loading.
Additionally, try setting an instance variable in the class body or in initialize
. You'll notice the latter will belong to the created object, whereas the first will belong to the class instance (hence the name class instance variable).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With