#=> class more
#繼承怎麼實現:
class LittleBird < Bird
def initialize name
super(name)
end
end
#特殊屬性訪問控制:
attr_reader :name
attr_writer :sex
#=> module
#interface怎麼寫:
#ruby沒有interface,只有比interface更強大的module與mixin機制
#=> module
#"有邏輯實現的interface":
module Eat
def eat
p "i can eat"
end
end
module Sleep
def sleep
p "i can sleep"
end
end
class Pig
include Eat
include Sleep
end
Pig.new.eat
Pig.new.sleep
#=> module constants
# module constants訪問:
module Math
PI = 3.14
end
Math::PI
#=> module more
# module namespace:
module Foo
module Bar
def self.say
p "Hi"
end
end
end
Foo::Bar.say
# another module namespace:
module Foo
class Bar
def say
p "Hi"
end
end
end
Foo::Bar.new.say
#=> module singleton
# module的特殊用法singleton:
module Item
extend self
def name
p "i'm item"
end
end
Item.name
#=> ruby more
# monkey patch:
class Fixnum
def plus n
self + n
end
end
1.plus 3
Ruby語言 (三)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.