简体   繁体   English

(class_eval,define_method)vs(instance_eval,define_method)的Ruby单例方法

[英]Ruby singleton methods with (class_eval, define_method) vs (instance_eval, define_method)

Metaprogramming in ruby is great because I constantly use it to emulate prototype based programming and quickly write prototype solutions to some problems to test their viability. 红宝石中的元编程很棒,因为我经常使用它来模仿基于原型的编程,并快速编写原型解决方案来测试某些问题以测试其可行性。 So I would like to know if there is any essential difference between the following pieces of code: 因此,我想知道以下代码段之间是否有本质区别:

(class << some_object; self; end).class_eval do
  define_method(:method_name) do ... method body ... end
end

and

(class << some_object; self; end).instance_eval do
  define_method(:method_name) do ... method body ... end
end

Both versions of the code define a singleton method and I haven't yet come up against anything that has forced me to choose the (instance_eval, define_method) combination over the (class_eval, define_method) combination to define a singleton method and I'm wondering if there is some essential difference between the two. 这两个版本的代码都定义了一个单例方法,我还没有遇到任何迫使我选择(instance_eval, define_method)组合而不是(class_eval, define_method)组合来定义一个单例方法的问题,我想知道两者之间是否有本质区别。

No difference for define_method . define_method没有区别。 But there is a difference when you use def . 但是使用def会有区别。

o = Object.new  

# class_eval example
class << o; self; end.class_eval { def test1;  :test1; end  }
o.test1 #=> test1

# instance_eval example
class << o; self; end.instance_eval { def test2; :test2; end }
o.test2 #=> NoMethodError

Why the difference in behaviour between def and define_method ? 为什么defdefine_method行为有所不同? define_method is a method call and so operates on the self in the eval context. define_method是一个方法调用,因此在eval上下文中对self进行操作。 The self in both instance_eval and class_eval is the same - it is the receiver (the eigenclass of o). self两个instance_evalclass_eval是相同的-它是接收机(邻的eigenclass)。

However def behaves differently, it does not operate on the self but instead on the default define . 但是def行为有所不同,它不会对self进行操作,而是对default define In the case of class_eval the default definee is the same as self but for instance_eval it is instead the metaclass of self . class_evaldefault definee下, default defineeself相同,但对于instance_eval它是self的元类。

How do we access the test2 method defined above? 我们如何访问上面定义的test2方法? test2 must be an instance method defined on the metaclass of the eigenclass of o. test2必须是在o的本征类的元类上定义的实例方法。

It is a class method on the eigenclass of o: 它是o的本征类的类方法:

class << o; test2; end #=> :test2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM