zoukankan      html  css  js  c++  java
  • yield self和instance_eval用法区别

    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
  • 相关阅读:
    Jakarta雅加达项目简介
    java的Commons包简介
    装饰者模式
    命令模式
    桥接模式
    适配器模式
    观察者模式
    模板模式
    责任链模式
    CentOS搭建NAT和DHCP服务,实现共享上网
  • 原文地址:https://www.cnblogs.com/or2-/p/5221740.html
Copyright © 2011-2022 走看看