ubuntu, ror, jQuery, css, website memo
太嫩, 沒啥心得, 用來紀錄每天學的
2009年5月1日 星期五
block, Proc , lambda AND module mixin AND method_missing
Ruby 程式語言簡介
帶參數的 code block
def call_block
yield(1)
yield(2)
yield(3)
end
call_block { |i|
puts "#{i}: Blocks are cool!"
}
# 輸出
# # "1: Blocks are cool!"
# # "2: Blocks are cool!"
# # "3: Blocks are cool!"
Proc object
將 code block 明確轉成物件
def call_block(&block)
block.call(1)
block.call(2)
block.call(3)
end
call_block { |i| puts "#{i}: Blocks are cool!" }
# 或是先宣告出 proc object
proc_1 = Proc.new { |i| puts "#{i}: Blocks are cool!" }
proc_2 = lambda { |i| puts "#{i}: Blocks are cool!" }
call_block(&proc_1)
call_block(&proc_2)
# 輸出
# "1: Blocks are cool!"
# "2: Blocks are cool!"
# "3: Blocks are cool!
Module 和 Mixins
module Debug
def who_am_i?
"#{self.class.name} (\##{self.object_id}): #{self.to_s}"
end
end
class Foo
include Debug # 這個動作叫做 Mixin
# ...
end
class Bar
include Debug
include AwesomeModule
# ...
end
ph = Foo.new("12312312")
et = Bar.new("78678678")
ph.who_am_i? # 輸出 "Foo (#330450): 12312312"
Method Missing
class Proxy
def initialize(object)
@object = object
end
def method_missing(symbol, *args)
@object.send(symbol, *args)
end
end
object = ["a", "b", "c"]
proxy = Proxy.new(object)
puts proxy.first
# Proxy 並沒有 first 這個函式,將執行 method_missing,並輸出 "a"
Introspection (反射機制)
# 這個物件有什麼函式
Object.methods
=> ["send", "name", "class_eval", "object_id", "new",
"singleton_methods", ...]
# 這個物件有這個函式嗎?
Object.respond_to? :name
=> true
沒有留言:
張貼留言
較新的文章
較舊的文章
首頁
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言