论坛首页 编程语言技术论坛

未绑定类举例和说明(浅析)

浏览 1400 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-02-27  
class Interpreter
  def do_a()
    print "there, ";
  end      
  def do_d()
    print "Hello ";
  end
  def do_e()
    print "!\n";
  end
  def do_v()
    print "Dave";
  end
  Dispatcher = {
    ?a => instance_method(:do_a),
    ?d => instance_method(:do_d),
    ?e => instance_method(:do_e),
    ?v => instance_method(:do_v)
  }
  def interpret(string)
    string.each_byte {|b| Dispatcher[b].bind(self).call }
  end
end

interpreter = Interpreter.new
interpreter.interpret('dave')


Returns an UnboundMethod representing the given instance method in mod.
Bind umeth to obj. If Klass was the class from which umeth was obtained, obj.kind_of?(Klass) must be true.

   class A
     def test
       puts "In test, class = #{self.class}"
     end
   end
   class B < A
   end
   class C < B
   end

   um = B.instance_method(:test)
   bm = um.bind(C.new)
   bm.call
   bm = um.bind(B.new)
   bm.call
   bm = um.bind(A.new)
   bm.call

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics