简体   繁体   English

为Singleton方法而不是Class方法添加的Methods_

[英]Methods_added for Singleton methods, but not Class methods

I'm really not understanding this Ruby Monk exercise : 我真的不了解Ruby Monk练习

There's an important nuance that's worth understanding when dealing with singleton_method_added and method_added. 在处理singleton_method_added和method_added时,有一个重要的细微差别值得理解。

The most natural tack the mind takes with these two callbacks is to assume that method_added will observe instance methods and singleton_method_added, class methods. 记住,这两个回调最自然的方法是假设method_added将观察实例方法和singleton_method_added类方法。 This, however, is not entirely true; 但是,这并不完全正确。 Ruby's singleton object backs normal objects and contains object specific changes. Ruby的单例对象支持普通对象,并且包含特定于对象的更改。 For classes, these are class methods. 对于类,这些是类方法。 But when adding a method to a single, regular object, adding instance methods to that object alone modifies the singleton object for that object. 但是,当将方法添加到单个常规对象时,仅将实例方法添加到该对象会修改该对象的单例对象。

Let me show you why by having you solve this exercise. 让我告诉您为什么要解决此练习。

The exercise is: 练习是:

AN_OBJECT = Object.new

def AN_OBJECT.methods_added
  @@methods_added ||= []
end

def AN_OBJECT.singleton_methods_added
  @@singleton_methods_added ||= []
end

My attempt was to do this: 我的尝试是这样做:

def AN_OBJECT.methods_added
  unless AN_OBJECT.is_a?(Class)
    @@methods_added ||= []
  end
end

def AN_OBJECT.singleton_methods_added
  if AN_OBJECT.instance_of?(Object)
    @@singleton_methods_added ||= []
  end
end

But the specs still fail. 但是规格仍然失败。

I'm really having trouble wrapping my head around what exactly they want me to do. 我真的很难解决他们到底要我做什么的问题。 What is a singleton object? 什么是单例对象? From what I understand, a singleton class is kind of a 'metaclass' that exists solely to give behavior to a certain instance of a class. 据我了解,单例类是一种“元类”,其存在仅仅是为了给类的某个实例赋予行为。

Is a singleton object a kind of 'metaobject' that exists solely to give behavior to a certain instance of an object? 单例对象是否是一种“元对象”,仅为了给对象的某个实例提供行为而存在? This is really confusing for me. 这真让我感到困惑。

Eureka! 找到了!

AN_OBJECT = Object.new

def AN_OBJECT.methods_added
  @@methods_added ||= []
end

def AN_OBJECT.singleton_methods_added
  @@singleton_methods_added ||= []
end

def AN_OBJECT.singleton_method_added(method_name)
  @@singleton_methods_added ||= []
  @@singleton_methods_added << method_name
end

If you look at the previous excercise if you scroll up, it should give you enough hint on how to handle it. 如果您向上滚动查看先前的练习,则应该为您提供足够的提示,说明如何进行操作。 It's a tragedy that I posted this so much later.. 我这么晚才发布这是一个悲剧。

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

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