Documente Academic
Documente Profesional
Documente Cultură
O
Overview
i
Next big topic is typing, classes, and
inheritance
But first, a couple of useful things
Shorthand
for getters/setters
An example of an each iterator
A little more about blocks vs
vs. Procs
G tt /S tt
Getters/Setters
class PosRat
def initialize(num, denom=1)
@num = num
@d
@denom
= denom
d
end
def num
@num
end
def num=(value)
@num = value
end
A Alternative
An
Alt
ti
Was:
def num
@num
end
def denom
@denom
end
There is a similar
attr writer shortcut
attr_writer
It t Example
Iterator
E
l
S
Sequence
Class
Cl
&C
Constructor
t t
class Sequence
# mixin all of the methods in Enumerable
include Enumerable
def initialize(from, to, step)
@from, @to, @step = from, to, step
end
d
S
Sequence
each
h method
th d
Bl k & Procs
Blocks
P
R i it d
Revisited
etc
etc.
This is exactly a closure
T
Types
in
i R
Ruby
b
Ruby is dynamically typed everything is
an object
j
Only notion of an objects type is what
messages it can respond to
i.e.,
D k Typing
Duck
T i
if it isnt
All that matters is how an object behaves
Th
Thought
ht E
Experiment
i
t (1)
Th
Thought
ht E
Experiment
i
t (2)
D k Typing
Duck
T i T
Tradeoffs
d ff
Plus
Convenient,
p
promotes
code reuse
All that matters is what messages an object can
receive
Minus
Obvious
Cl
Classes
& IInheritance
h it
Ruby vs Java:
Subclassing
O
Overriding
idi
With dynamic typing, inheritance alone is
jjust avoiding
g cut/paste
p
Overriding is the key difference
When
R b Di
Ruby
Digression
i