Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: initialize() vs class body?

Tags:

ruby

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 
like image 918
gjb Avatar asked May 18 '11 11:05

gjb


People also ask

What does initialize method do in Ruby?

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.

What is new () in Ruby?

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 .

What is instantiation of a class in Ruby?

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)

What is class New in Ruby?

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.


2 Answers

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.

like image 130
ceth Avatar answered Oct 14 '22 12:10

ceth


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

like image 33
Michael Kohl Avatar answered Oct 14 '22 10:10

Michael Kohl