码迷,mamicode.com
首页 > 其他好文 > 详细

yield self和instance_eval用法区别

时间:2016-02-26 22:03:19      阅读:366      评论:0      收藏:0      [点我收藏+]

标签:

class Foo
    def initialize(&block)
      instance_eval(&block) if block_given?
    end
  end
class Foo
  def initialize
    yield self if block_given?
  end
end
x = Foo.new {|obj| def obj.foo() foo end}
x.foo

 By using instance_eval you‘re evaluating the block in the context of your object. This means that using def will define methods on that object. It also means that calling a method without a receiver inside the block will call it on your object.

使用 instance_eval 对象是执行代码快的上下文,意味着使用del 定义方法在对象上,意味着没有使用接收者调用方法,对象就是接收者

When yielding self you‘re passing self as an argument to the block, if your block doesn‘t take any arguments, it is simply ignored. 

当使用yield self时,传递self作为参数给代码快,如果代码快没有接收任何参数,那么self就被忽略,

 例子

class Thing
  attr_accessor :name

  def initialize
    yield self if block_given?
  end



end


def given(foo:)
  yield(Thing.new do |thing|
    thing.name=foo
  end)
end


given(foo: jack) do |thing|
  p thing.name
end

 

yield self和instance_eval用法区别

标签:

原文地址:http://www.cnblogs.com/or2-/p/5221740.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!