I’m trying to wrap my head around the purpose of using the initialize method. In Hartl’s tutorial, he uses the example:
def initialize(attributes = {})
@name = attributes[:name]
@email = attributes[:email]
end
Is initialize setting the instance variables @name and @email to the attributes, and, if so, why do we have the argument attributes = {}?
Ruby uses the
initializemethod as an object’s constructor. It is part of the Ruby language, not specific to the Rails framework. It is invoked when you instanstiate a new object such as:Calling the
newclass level method on aClassallocates a type of that class, and then invokes the object’sinitializemethod:http://www.ruby-doc.org/core-1.9.3/Class.html#method-i-new
All objects have a default
initializemethod which accepts no parameters (you don’t need to write one – you get it automagically). If you want your object to do something different in theinitializemethod, you need to define your own version of it.In your example, you are passing a hash to the
initializemethod which can be used to set the default value of@nameand@email.You use this such as:
The reason the initializer has a default value for attributes (
attributes = {}sets the default value to an ampty hash –{}) is so that you can also call it without having to pass an argument. If you dont’ specify an argument, thenattributeswill be an empty hash, and thus both@nameand@emailwill benilvalues as no value exists for those keys (:nameand:email).