• 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
  • 相关阅读:
    安装Hadoop单机版
    Linux的en33没有IP地址
    idea导入spring源码
    CSS 选择器之基础选择器
    CSS 简介和代码风格
    JavaScript 中 双感叹号 !! 的作用
    VS Code 中的settings.js 配置
    项目中使用 vuex 实现(状态)数据共享
    VS Code 相关设置
    Node.js 的简单了解
  • 原文地址:https://www.cnblogs.com/or2-/p/5221740.html
Copyright © 2020-2023  润新知