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
  • 相关阅读:
    python匹配中文和非中文
    Django mysql连接错误
    linux搭建postfix邮件服务器
    linux编译安装redis
    python将py文件打包成可运行的exe文件
    mysql表结构自动生成golang struct
    linux离线安装nginx+uwsgi
    Sass/Scss
    CSS变量和浏览器前缀
    CSS中常用的函数
  • 原文地址:https://www.cnblogs.com/or2-/p/5221740.html
Copyright © 2011-2022 走看看