ruby object model

100
Ruby Object Model Chhorn Chamnap Yoolk Mango 4 Aug 2010

Upload: chamnap-chhorn

Post on 19-May-2015

5.127 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: Ruby object model

Ruby Object Model

Chhorn ChamnapYoolk Mango4 Aug 2010

Page 2: Ruby object model

Agenda

Basic Ruby Methods Classes Method-Access Rules What’s in an Object? Classes in Depth What Happens When You Call a Method? Module Constants Self Scope Singleton Method

Page 3: Ruby object model

Basic Ruby

Page 4: Ruby object model

Variables

Local variables start with a lowercase letter or an underscore

Eg: x, string, __abc__, start_value, and firstName

Ruby convention is to use underscores with multiple words (first_name)

can't start with an uppercase letter Instance variables

storing information for individual objects always start with a single at-sign(@) can start with an uppercase letter

Page 5: Ruby object model

Variables (cont.)

Class variables store information per class hierarchy follow the same rules as instance

variables start with two at-signs: @@running_total

Global variables recognizable by their leading dollar sign

($) $:, $1, and $/, $stdin and $LOAD_PATH

Page 6: Ruby object model

Keywords

predefined, reserved terms associated with specific programming tasks and contexts. def, class, if, and __FILE__

Page 7: Ruby object model

Things look like local variables

Ruby interprets it as one of three things: A local variable A keyword 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.

Page 8: Ruby object model

Interpreter command-line switches

Page 9: Ruby object model

“Load”-ing a file

When you load a file, Ruby looks for it in each of its load path.

The last directory is the current directory. load is a method. Load file from relative directories

load "../extras.rb" load "/home/users/dblack/book/code/loadee.rb"

A call to load always loads the file you ask for. Good to examine the effect of changes

immediately.

Page 10: Ruby object model

“Require”-ing a feature

Doesn’t reload files if already loaded. require "loadee" require "/home/users/code/loadee"

Page 11: Ruby object model

Methods

Page 12: Ruby object model

Method names

Follow the same rules and conventions as local variables 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.

Page 13: Ruby object model

Method calls

Ruby sees all data structures and values as objects. 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.

Page 14: Ruby object model

Method arguments

Have to supply the correct number of arguments.

Page 15: Ruby object model

Optional arguments

A method that allows any number of arguments.

def multi_args(*x)puts "I can take zero or more arguments!"

end

multi_args(1,2,4)multi_args(1,2)

Page 16: Ruby object model

Default values for arguments

def default_args(a,b,c=1)puts "Values of variables: ",a,b,c

end

default_args(3,2)

Page 17: Ruby object model

Order of parameters and arguments

Ruby tries to assign values to as many variables as possible.

The sponge parameters get the lowest priority.

Page 18: Ruby object model

Order of parameters and arguments (cont.)

Page 19: Ruby object model

Order of parameters and arguments (cont.)

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

def broken_args(x,*y,z=1)end

syntax error

Page 20: Ruby object model

Method signatures

Page 21: Ruby object model

Classes

Page 22: Ruby object model

Objects and Classes

Classes define clusters of behavior or functionality.

Classes can respond to messages, just like objects.

Objects can change, acquiring methods and behaviors that were not defined in their class.

Page 23: Ruby object model

Classes

In Ruby, classes are objects. The new method is a constructor. Classes are named with constants.

Page 24: Ruby object model

Inside Class Definitions

Ruby executed the code within the class just as it would execute any other code.

Page 25: Ruby object model

Reopening classes

It’s possible to reopen a class and make additions or changes.

Page 26: Ruby object model

Instance methods

These methods defined inside a class.

Used by all instances of the class. They don’t belong only to one object.

Page 27: Ruby object model

Instance variables

Enables individual objects to remember state.

Always start with @. Visible only to the object to which

they belong. Initialized in one method definition is

the same as in other method definitions.

Page 28: Ruby object model

Instance variables (cont.)

Page 29: Ruby object model

Initializing an object with state

Define a special method called initialize.

Page 30: Ruby object model

Setter methods

Ruby allows you to define methods that end with an equal sign (=).

ticket.price=(63.00)ticket.price = 63.00

def price=(amount) @price = amountend

Page 31: Ruby object model

The attr_* methods

The attributes are implemented as reader and/or writer methods.

Page 32: Ruby object model

The attr_* methods (cont.)

Page 33: Ruby object model

Inheritance

Ruby supports only single inheritance.

Classes can import modules as mixins.

The class Object is almost at the top of the inheritance chart.

Page 34: Ruby object model

Method-Access Rules

Page 35: Ruby object model

Private methods

• PRIVATE METHODS CAN’T BE CALLED WITH AN EXPLICIT RECEIVER.

class Baker def bake_cake pour_flour add_egg end def pour_flour end def add_egg end private:

pour_flour, :add_eggend

class Baker def bake_cake pour_flour add_egg endprivate: def pour_flour end def add_egg endend

Page 36: Ruby object model

Private setter (=) methods

It’s OK to use an explicit receiver for private setter methods.

Page 37: Ruby object model

Protected methods

Page 38: Ruby object model

Top-level method

The top-level method is stored as a private instance method of the Object class.

Page 39: Ruby object model

What’s in an Object?

Page 40: Ruby object model

What’s in an Object?

Every object is “born” with certain innate abilities. object_id respond_to? send methods instance_variables

Page 41: Ruby object model

Object Model Diagram

Page 42: Ruby object model

The send method

Not uncommon to define a method called send. Then, use __send__ instead.

public_send, a safe version of send method.

send can call an object’s private methods public_send can’t.

Page 43: Ruby object model

Classes in Depth

Page 44: Ruby object model

Classes as objects

Every class is an instance of a class called Class.

You can also create a class the same way you create most other objects.my_class = Class.newinstance_of_my_class = my_class.new

Page 45: Ruby object model

Object Model Diagram (cont.)

Page 46: Ruby object model

Object Model Diagram (cont.)

Page 47: Ruby object model

The chicken-and-egg paradox

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

Page 48: Ruby object model

Class and object Roundup

Classes are objects. Instances of classes are objects, too. A class object has its own methods,

its own state, its own identity.

Page 49: Ruby object model

What Happens When You Call a Method?

Page 50: Ruby object model

What Happens When You Call a Method?

When you call a method, Ruby does two things: It finds the method (method lookup). It executes the method. (find self).

Page 51: Ruby object model

Method Lookup

“one step to the right, then up.”

Page 52: Ruby object model

How objects call their methods?

How objects call their methods? From their class From the superclass and earlier ancestors of

their class 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.Ticket.new

Page 53: Ruby object model

How objects call their methods? (cont.)

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.class Ticket attr_reader :venue, :date attr_accessor :price

Page 54: Ruby object model

Module

Page 55: Ruby object model

Module

Modules are bundles of methods and constants.

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.

Page 56: Ruby object model

Module (cont.)

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

A class can mix in more than one module.

Page 57: Ruby object model

Method Lookup

Page 58: Ruby object model

The rules of method lookup

To resolve a message into a method: Its class Modules mixed into its class The class’s superclass Modules mixed into the superclass Likewise, up to Object (and its mix-in

Kernel) and BasicObject

Page 59: Ruby object model

Defining the same method more than once

Define a method twice inside the same class, the second definition takes precedence.class D def hello puts “hello” endend

class D def hello puts “hello world” endend

Page 60: Ruby object model

Defining the same method more than once (cont.)

If the object’s method-lookup path includes more than two same methods, the first one is the “winner”.

Page 61: Ruby object model

Defining the same method more than once (cont.)

A class mixes in two or more modules. The modules are searched in reverse

order of inclusion

Page 62: Ruby object model

Including the same module more than once

Re-including a module doesn’t do anything.

N is still considered the most recently included module.

class C include M include N include Mend

Page 63: Ruby object model

The super keyword

Use the super keyword to jump up to the next-highest definition, in the method-lookup path.

Page 64: Ruby object model

The super keyword (cont.)

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)

Page 65: Ruby object model

The method_missing method The Kernel module provides an instance method

called method_missing.

Page 66: Ruby object model

Nesting modules and classes

Nested module/class chains are used to create namespaces for classes, modules, and methods.module Tools class Hammer endEnd

h = Tools::Hammer.new

Page 67: Ruby object model

Constants

Page 68: Ruby object model

Constants

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 class methods.

Page 69: Ruby object model

Modifying constants

You get a warning if you reassign to the constant.

To modify a constant, use a variable instead.

not redefining a constant, good for reloading program files

Page 70: Ruby object model

Scope of constants

Constants have a kind of global visibility or reachability.

Bears a close resemblance to searching a filesystem.

Page 71: Ruby object model

Scope of constants (cont.)

Like /, the :: means “start from the top level.”

Page 72: Ruby object model

Self

Page 73: Ruby object model

Self

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.

Page 74: Ruby object model
Page 75: Ruby object model

Self (cont.)

Page 76: Ruby object model

The top-level self object

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.

main is a special term that the default self object.

The keyword (class, module, or def) marks a switch to a new self.

ruby -e 'puts self'

Page 77: Ruby object model

Self in class and module definitions

In a class or module definition, self is the class or module object.

Page 78: Ruby object model

Self in instance method definitions

In a method definition, self is the object that called it.

Page 79: Ruby object model

Self in singleton method definitions

When a singleton method is executed, self is the object that owns the method.

Page 80: Ruby object model

Self as the default receiver of messages

If the receiver of the message is self, you can omit the receiver and the dot.

Page 81: Ruby object model

Self as the default receiver of messages (cont.)

If both a method and a variable of a given name exist (talk), the variable takes precedence. 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 object-dot-notation.self.first_name = “dara”first_name = “dara”

Page 82: Ruby object model

Instance variables

Every instance variable belongs to self.

Page 83: Ruby object model
Page 84: Ruby object model

Scope

Page 85: Ruby object model

Scope

Scope refers to the reach or visibility of variables and constants.

Three types of variables: global, local, and class variables.

Page 86: Ruby object model

Global scope

Global scope is scope that covers the entire program.

Global scope is enjoyed by global variables.

Page 87: Ruby object model

Local scope

Local scope is a basic layer of every Ruby program.

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 local scope. Every method definition has its own local

scope.

Page 88: Ruby object model
Page 89: Ruby object model

Local scope (cont.)

Page 90: Ruby object model

Class variables

Provides a storage mechanism shared between a class and its instances.

Visible only to a class and its instances.

Page 91: Ruby object model
Page 92: Ruby object model

Class variables (cont.)

They’re class-hierarchy variables.

Page 93: Ruby object model
Page 94: Ruby object model

Singleton method

Page 95: Ruby object model

Singleton method

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.

Page 96: Ruby object model

More about singleton methods

Where do singleton methods live? The singleton class

Every object has two classes: The class of which it’s an instance Its singleton class

Page 97: Ruby object model

More about singleton methods (cont.)

Singleton classes are anonymous. The << object notation means the

anonymous, singleton class of object.

Page 98: Ruby object model

More about singleton methods (cont.)

Page 99: Ruby object model

Singleton classes on the method-lookup path

Page 100: Ruby object model

References

The Well-Grounded Rubyist, David A. Black

Metaprogramming Ruby, Paolo Perrotta