ruby - 实例评估 : why the class of subclass is superclass

标签 ruby

    def singleton_class
       class << self
         self
       end
    end

    class Human
      proc = lambda { puts 'proc says my class is ' + self.name.to_s }

      singleton_class.instance_eval do
        define_method(:lab)  do 
          proc.call
        end
      end
    end

    class Developer < Human
    end

    Human.lab # class is Human
    Developer.lab # class is Human ; oops

以下解决方案有效。

def singleton_class
  class << self
    self
  end
end

class Human
  proc =  lambda { puts 'proc says my class is ' + self.name.to_s }
  singleton_class.instance_eval do
    define_method(:lab) do
      self.instance_eval &proc
    end
  end
end

class Developer < Human
end

Human.lab # class is Human
Developer.lab # class is Human ; oops

为什么 Developer.lab 报告它是人类?以及可以做什么,以便在调用 Developer.lab 时 proc 报告 Developer。

最佳答案

它很微妙,但它归结为简单地调用 block (在这种情况下它充当一个普通的闭包,并且 self 对应于它被定义的位置,即在 Human),或(直接)将其用作方法定义或 instance_eval 的 block :

def singleton_class
   class << self
     self
   end
end


class Human

  PROC = proc { puts 'proc says my class is ' + self.name.to_s }

  singleton_class.instance_eval do
    define_method(:lab)  do 
      PROC.call
    end
    define_method(:lab2, &PROC.method(:call))

    define_method(:lab3)  do 
      instance_eval(&PROC)
    end
    define_method(:lab4, &PROC) 
  end
end

class Developer < Human
end

Human::PROC.call  # => "class is Human"  (original closure)
Developer.lab     # Same as previous line, so "class is Human"  (original closure)
Developer.lab2    # ditto

Developer.instance_eval(&Human::PROC)  # => "class is Developer"  (instance_eval changes sets a different scope)
Developer.lab3    # Same as previous line, so "class is Developer"
Developer.lab4    # ditto

关于ruby - 实例评估 : why the class of subclass is superclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2758513/

相关文章:

ruby-on-rails - Rails 5,设计嵌套属性,不允许的参数

ruby - 有人可以解释一下在 Ruby 中注入(inject)的真实、通俗易懂的用法吗?

ruby-on-rails - 查询适用于 MySQL 但不适用于 Postgresql

ruby-on-rails - 使用 foreach 函数从 csv 文件中读取数据

ruby-on-rails - Rspec View 未定义方法 stub_model

ruby-on-rails - Bash to Ruby - 使用 whois 和 grep 命令获取列表

ruby-on-rails - 测试我的 Ruby gem:Shoulda::Matchers:Module (NoMethodError) 的未定义方法 `configure'

ruby-on-rails - 如何使用基于语言的 View 和模板?

c - Rake 构建 C 应用程序

ruby-on-rails - 使用 rails 模型中的关联定义的 finder_sql 进行分页