What’s in an Object?
Classes in Depth
What Happens When You Call a Method?
start with a lowercase letter or an underscore
Eg: x, string, __abc__, start_value, and firstName
Ruby convention is to use underscores with multiple
can't start with an uppercase letter
storing information for individual objects
always start with a single at-sign(@)
can start with an uppercase letter
store information per class hierarchy
follow the same rules as instance variables
start with two at-signs: @@running_total
recognizable by their leading dollar sign ($)
$:, $1, and $/, $stdin and $LOAD_PATH
predefined, reserved terms associated with
specific programming tasks and contexts.
Ruby interprets it as one of three things:
A local variable
A method call
Here’s how Ruby decides:
1. If the identifier is a keyword, it’s a keyword.
2. If there’s an equal sign (=) to the right of the
identifier, it’s a local variable.
3. Otherwise, assumed to be a method call.
When you load a file, Ruby looks for it in each of its
The last directory is the current directory.
load is a method.
Load file from relative directories
A call to load always loads the file you ask for.
Good to examine the effect of changes immediately.
Follow the same rules and conventions as
except, can end with ?, !, or =
Methods are expressions that provide a value.
In some contexts, you can’t tell, just by
looking at an expression.
Ruby sees all data structures and values as
x = "100".to_i(9)
Methods can take arguments.
Parentheses are usually optional.
Many programmers use parentheses in most or all
method calls, just to be safe.
Have to supply the correct number of
A method that allows any number of
puts "I can take zero or more arguments!"
puts "Values of variables: ",a,b,c
Ruby tries to assign values to as many variables
The sponge parameters get the lowest priority.
Required ones get priority, whether they
occur at the left or at the right of the list.
All the optional ones have to occur in the
Classes define clusters of behavior or
Classes can respond to messages, just like
Objects can change, acquiring methods and
behaviors that were not defined in their class.
In Ruby, classes are objects.
The new method is a constructor.
Classes are named with constants.
Ruby executed the code within the class just
as it would execute any other code.
It’s possible to reopen a class and make
additions or changes.
These methods defined inside a class.
Used by all instances of the class.
They don’t belong only to one object.
Enables individual objects to remember state.
Always start with @.
Visible only to the object to which they
Initialized in one method definition is the
same as in other method definitions.
Define a special method called initialize.
Ruby allows you to define methods that end
with an equal sign (=).
def price=(amount) ticket.price=(63.00)
@price = amount ticket.price = 63.00
The attributes are implemented as reader
and/or writer methods.
Ruby supports only single inheritance.
Classes can import modules as mixins.
The class Object is almost at the top of the
• Private methods can’t be called with an explicit receiver.
class Baker class Baker
def bake_cake def bake_cake
def pour_flour private
end def pour_flour
def add_egg end
end def add_egg
private: pour_flour, end
It’s OK to use an explicit receiver for private
The top-level method is stored as a private
instance method of the Object class.
Every object is “born” with certain innate
Not uncommon to define a method called
Then, use __send__ instead.
public_send, a safe version of send method.
send can call an object’s private methods
Every class is an instance of a class called
You can also create a class the same way you
create most other objects.
my_class = Class.new
instance_of_my_class = my_class.new
The class Class is an instance of itself.
Object is a class, Object is an object.
And Class is a class. And Object is a class, and
Class is an object.
Which came first?
Ruby has to do some of this chicken-or-egg stuff
in order to get the class and object system up and
Classes are objects.
Instances of classes are objects, too.
A class object has its own methods, its own
state, its own identity.
When you call a method, Ruby does two
It finds the method (method lookup).
It executes the method. (find self).
“one step to the right, then up.”
How objects call their methods?
From their class
From the superclass and earlier ancestors of their
From their own store of singleton methods
Instances of Class can call methods that are
defined as instance methods in their class.
Class defines an instance method called new.
The class Class has two new methods as:
a class method; Class.new
an instance method; Ticket.new
Instances of Class have access to the instance
methods defined in Module.
attr_reader :venue, :date
Modules are bundles of methods and
Modules don’t have instances.
Consists of the functionality to be added to a
class or an object.
Modules encourage modular design.
Modules are the more basic structure, and
classes are just a specialization.
Modules get mixed in to classes, using the
include method, referred to as mix-ins.
The instances of the class have the ability to
call the instance methods defined in the
A class can mix in more than one module.
To resolve a message into a method:
Modules mixed into its class
The class’s superclass
Modules mixed into the superclass
Likewise, up to Object (and its mix-in Kernel) and
Define a method twice inside the same class,
the second definition takes precedence.
puts “hello world”
If the object’s method-lookup path includes
more than two same methods, the first one is
A class mixes in two or more modules.
The modules are searched in reverse order of
Re-including a module doesn’t do anything.
N is still considered the most recently
Use the super keyword to jump up to the
next-highest definition, in the method-
The way super handles arguments:
Called with no argument list – super
Called with an empty argument list – super()
Called with specific arguments – super(a,b,c)
The Kernel module provides an instance method called
Nested module/class chains are used to
create namespaces for classes, modules, and
h = Tools::Hammer.new
Begin with an uppercase letter.
eg: A, String, FirstName, and STDIN
(FirstName) or (FIRST_NAME) is usual.
Can be referred to from inside the instance or
You get a warning if you reassign to the
To modify a constant, use a variable instead.
not redefining a constant,
good for reloading program files
Constants have a kind
of global visibility or
Bears a close
searching a filesystem.
Like /, the :: means “start from the top level.”
At every moment, only one object is playing
the role of self.
Self is the default object or current object.
To know which object is self, you need to
know what context you’re in.
But what is self when you haven’t yet entered
any definition block?
The answer is that Ruby provides you with a start-
up self at the top level.
ruby -e 'puts self'
main is a special term that the default self
The keyword (class, module, or def) marks a
switch to a new self.
In a class or module definition, self is the class
or module object.
In a method definition, self is the object that
When a singleton method is executed, self is
the object that owns the method.
If the receiver of the message is self, you can
omit the receiver and the dot.
If both a method and a variable of a given
name exist (talk), the variable takes
To force Ruby to see as a method name, you’d
have to use self.talk or talk().
To call a setter method, have to supply
self.first_name = “dara”
first_name = “dara”
Every instance variable belongs to self.
Scope refers to the reach or visibility of
variables and constants.
Three types of variables: global, local, and
Global scope is scope that covers the entire
Global scope is enjoyed by global variables.
Local scope is a basic layer of every Ruby
Every time you cross into a class, module, or
def keyword, you start a new local scope.
The top level has its own local scope.
Every class or module definition block has its own
Every method definition has its own local scope.
Provides a storage mechanism shared
between a class and its instances.
Visible only to a class and its instances.
They’re class-hierarchy variables.
Let’s say we’ve created our Ticket class.
Ticket isn’t only a class.
Ticket is also an object in its own right.
defined directly on the class object Ticket.
referred to as a class method of the class.
Where do singleton methods live?
The singleton class
Every object has two classes:
The class of which it’s an instance
Its singleton class
Singleton classes are anonymous.
The << object notation means the anonymous,
singleton class of object.
The Well-Grounded Rubyist, David A. Black
Metaprogramming Ruby, Paolo Perrotta