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