Download - Constructors, Intro to Ruby Classes Part II
RUBY constructors,Intro to Ruby Classes, Part II
By Juan Leal@terminalbreaker
November 2013
Intro
Juan LealSoftware developer since 2001, Ruby developer since 2007
Worked in large corporations and small businesses.
Worked in various industries.
Worked on over a dozen software projects, many mission critical.
Ruby is a bit different
Many languages use a 'new' keyword which Ruby does not have to create an object instance.
Ruby instead provides a method 'new' which is called directly on a class.
Ruby is not strictly typed so there's no need to identify the data type.
Ruby does allocate space and create an instance of the class
Ruby constructor
It has three jobsIt allocates space for the object
It assigns instances variables their initial values
It returns the instance of that class
What a second!? Why are talking about 'initialize' all of a sudden? I thought we were talking about 'new'?
#initialize vs .new
#initialize is an instance method
.new is a class method
.new
Remember .new and it's three jobs?It allocates space for a new instance of the class
It assigns instances variables their initial values
It returns the instance of that class
Let's try and implement this ourselves and write our owncustom constructor.
Our own custom constructor is functionally equivalent to the default constructor
Both constructors return an instance of class Foo with their instance variables set.
This knowledge can help us do some pretty neat thing as we'll soon see.
Constructor overloading...sort of
One of the things I used to miss when I started working in Ruby was the ability to overload constructors. Strictly speaking overloading uses the same constructor method name but uses a different signature or parameter list.
We can accomplish a similar goal by creating our own custom constructors.
Here we can see our custom constructors in action.
Singleton Class
A Singleton class is a special class for which there can only exist one instance at anytime.Ruby implements this as a module which you can include.
Creating Singletons from Scratch
Here we implement our own singleton. We override Single.new with our own version, inside we assign @instance a new instance of the class Single by calling .allocate, unless it has already be assigned. Then the result is returned.
Thus only one instance is ever returned.
Summary
The ruby constructor performs 3 jobs; allocates space, assigns instance variables, returns the instance.
.new is a class method; #initialize is an instance method
.new is the constructor and #initialize is used to assign instance variables.
You can write your own constructors and singleton classes.
Thanks!
Questions???
Feel free to follow me on twitter. Every once in while I say something somewhat entertaining: @terminalbreaker
Feel free to post questions and comments on Meetup.com
Slides will be uploaded soon and I'll notify you all when it's done.