简体   繁体   English

Ruby eigenclass(s​​igleton类)创建了吗? 为了哪个?

[英]Ruby eigenclass (sigleton class) created? For which?

Got confused on Ruby meta-programming. 对Ruby元编程感到困惑。

So from the tutorial I learnt the following: 所以从本教程我学到了以下内容:

cat = "kitty"
cat.upcase  # "KITTY"
cat.poop    # undefined 'poop'

def cat.poop
  puts 'pooooooo...'
end

cat.upcase  # "KITTY"
cat.poop    # "pooooooo..."

So this means poop method is already for the cat object, which is of class String . 所以这意味着poop方法已经用于cat对象,它是String类。 From the famous textbook "Programming Ruby", by defining cat.poop , what actually happens is Ruby created an anonymous class, aka singleton or eigenclass, that is now the class of the cat object, then the original String class becomes the superclass of the newly created eigenclass. 从着名的教程 “Programming Ruby”,通过定义cat.poop ,实际发生的是Ruby创建了一个匿名类,也就是单例或本征类,现在是cat对象的类,然后原始的String类成为了类的超类。新创造的本征类。

Then this confused me. 然后这让我很困惑。 See the following code: 请参阅以下代码:

cat.poop    # "pooooooo...", it works, for sure
cat.class   # "String" | but this is NOT some other class

cat = "kate"
cat.poop    # poop not defined

3 questions: 3个问题:

  1. it does not look like there is any new class was ever created when defining the poop method. 在定义poop方法时,看起来没有创建任何新类。 Or maybe the it was created, but the "#class" method automatically redirected the call to the superclass' #class? 或者它可能是创建的,但“#class”方法会自动将调用重定向到超类'#class? Which is correct? 哪个是对的? How do we check? 我们如何检查?

  2. if we define another method, say cat.run , then will another eigenclass created or not? 如果我们定义另一个方法,比如cat.run ,那么是否会创建另一个本征类? What will be the class hierarchy then? 那么类层次结构会是什么?

  3. if cat is redefined to "kate", the poop is not found. 如果将重新定义为“kate”,则找不到大便 Why? 为什么? Shouldn't the poop be available to cat? 如果不是船尾提供给猫吗?

Thanks! 谢谢!

  1. Look at cat.singleton_class and cat.singleton_methods . 看看cat.singleton_classcat.singleton_methods
  2. No. Define a couple singleton methods on cat and then look at cat.singleton_class.instance_methods and you'll see them both there. 不。在cat上定义几个单例方法,然后查看cat.singleton_class.instance_methods ,你会在那里看到它们。 You can get a hint about the hierarchy with cat.singleton_class.ancestors . 您可以使用cat.singleton_class.ancestors获取有关层次结构的提示。
  3. You've defined cat to be some entirely new object now. 你现在已经将cat定义为一些全新的对象。 Why would it have the same methods? 为什么它有相同的方法? If you say cat = "string" then you can call cat.upcase , but if you later reassign cat = 5 , of course you can't still call cat.upcase . 如果你说cat = "string"那么你可以调用cat.upcase ,但是如果你以后重新分配cat = 5 ,当然你还是不能调用cat.upcase

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

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