ruby programming language(ch7)
Ch7
class def
last expression in def is the value of class def(nil if last is a method def)
init
|
|
attr
attr_reader :x, :yattr_accessor "x", "y"
duck type
loosen:
|
|
strict(for duck type):
|
|
coerce
class operation cannot hanle like other_class + self_class:
|
|
enum
|
|
thus utilize methods in include Enumerable based on each
equality
equal:
|
|
identity:
|
|
order
|
|
quick mutable
via Struct(core ruby class):
|
|
class method
|
|
var
constant:
FOO = Point.new(..)(initializemust be defined before)Point::BAR = ..outside define is ok
class var:
@@init in class def- available in both instance & class method
class instance var:
@init in class def- only available in class method
class << self; attr_accessor :..; end
method visibility
|
|
inherit
tips:
class derive < baseonly ‘public’ inheritany_class.class # => Classinstance_of Classany_class.superclass # => Objectsubclass_of Object
override
alias :super_inv :super_method_to_be_overridedto call method of superclass- only subclass when familiar with it (private methods can be occasionaly overrided!), or encapsulate/delegate if only to use public API
- class method also override, better to invoke it through the class which defines it
var
- instance var
- not inherited
- create on assign(usually done by method invoke)
- if same name, that value is overwritten not shadowed
- class instance var
- not inherited
- class var
- inherited, so alterable in subclass
- better to use class instance var instead, to avoid the above case
- constant
- bound to lexical scope within method(inherited method use constant of superclass)
object create
clonecan keep the frozen state whiledupnot- both use
initialize_copy(consider copy-constructor)
|
|
module
A named group of methods, contants and class vars.
|
|
allow nesting with classes
mixin
- module defines bunch of method rely on some class instance methods(as interface)
include modulein class- define the relied methods
- include module in module
object.extend(module)apply on a object
loading
| term | require | load |
|---|---|---|
| allow binary | Y | N |
| path | library name | exact filename |
| repeat | once | mutiple times |
| $SAVE level | 0 | current |
lazyload
|
|
eigenclass
- anonymouse class attached to an object, to open it
class << some; def .. end end class << class_namedefine class method of class_name or within class defclass << selfclass << objectdefine singleton method of object
method lookup
take o.m, search sequently:
- eigenclass of
ofor singleton methodm - instance method
m - modules (reverse the include order)
- inheritance (repeat 2-3)
- lookup
method_missing
constant lookup
- lexical
- inheritance:
.. -> Object(as top level) -> Kernel
example:
|
|