Ruby 请教一个关于 lambda 和 Proc

ericzhu · 2012年04月20日 · 最后由 EricZhu 回复于 2012年04月20日 · 2718 次阅读

直接上代码吧

class A   
   class B
      def initialize(&blk)
         define_singleton_method(:method_a, blk)
      end
   end

   def method_a
      p "method_a"
   end

   def create_b
      B.new{ method_a }
   end
end

A.new.create_b.method_a
#SystemStackError: stack level too deep

class A::B
   def initialize(&blk)
      define_singleton_method(:method_a, ->{blk.call})
   end
end
A.new.create_b.method_a
#method_a

第一个把 method_a 带进去 define_singleton_method 的第二个参数. 等价于:

define+singleton_method :method_a do 
  method_a
end

第二个把 p "method_a"带进去 define_singleton_method 的第二个参数. 等价于:

define+singleton_method :method_a do 
  puts "method_a"
end

相关例子:

class A
  def method1
        method1
  end
end
A.new.method1

ps,例子好像没有涉及 lambda 和 Proc 的区别. 第一个改成

def initialize(&blk)
  bk = Proc.new{blk.call}
  define_singleton_method(:method_a, bk)
end

也是可以和第二个一样的。

create_b 输出 self, 就清楚了。

def create_b
   B.new{ puts "self = #{self}"; method_a }
end


第一种情况 输出

self =  #<A::B:0xb48940>

第二种情况 输出

self = #<A:0xb487a8>

#1 楼 @yeerkunth #2 楼 @wx1452 十分感谢两位的解答

需要 登录 后方可回复, 如果你还没有账号请 注册新账号