2. Intro
Juan Leal
•
Software 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.
3. 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
4. Ruby constructor
●
It has three jobs
–
It 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'?
6. .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 own
custom constructor.
7. ●
●
●
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.
8. 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.
9. We can accomplish a similar goal by creating our own custom constructors.
10. Here we can see our custom constructors in action.
11. 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.
12. 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.
13. 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.
14. 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.