嵌套类如何在Ruby中访问外部类中的方法? [英] How can a nested class access a method in the outer class in Ruby?

查看:161
本文介绍了嵌套类如何在Ruby中访问外部类中的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def class A
  def a
    raise "hi" #can't be reached
  end

  class B
    def b
      a() #doesn't find method a.
    end
  end
end

我想从b调用a并引发异常.我该怎么办?

I want to invoke a from b and raise the exception. How can I?

推荐答案

Ruby没有嵌套的类.

Ruby doesn't have nested classes.

唯一继承行为的方法就是通过继承.

The only way to inherit behavior is, well, via inheritance.

如果您想让代码正常工作,则需要使用支持嵌套类的语言.虽然这是一个令人难以置信的强大的功能,但不幸的是,我只知道两种具有嵌套类的语言:

If you want your code to work, you need to use a language which supports nested classes. While this is an incredibly neat and powerful feature, I unfortunately know of only two languages that have nested classes:

  • BETA ,它是引入嵌套类的语言(及其后继的新闻
  • BETA, the language which introduced nested classes (and its successor gbeta)
  • Newspeak

我一无所知.

Java有一个称为嵌套类的构造,但不幸的是,它们在设计方面有局限性.

Java has a construct called nested classes, but they have some unfortunate design limitations.

在上面的示例中,嵌套在A内的不是 class B ,而是嵌套在 constant B >.考虑一下:

In your example above, it's not the class B that is nested inside A, it is the constant B that is nested inside A. Think about this:

C = A::B

现在,该类在两个名称下可用:A::BC.显而易见,C是全局的,并且没有嵌套在A内部. (实际上,C嵌套在Object内,因为也没有真正的全局常量,但这并不重要.)但是,由于CA::B是同一类,因此显然不能既嵌套又不嵌套.唯一合乎逻辑的结论是,类本身没有嵌套.

Now, the class is available under two names: A::B and C. It should be immediately obvious that C is global and not nested inside A. (Well, actually, C is nested inside Object, because there aren't really global constants either, but that's beside the point.) But since C and A::B are the same class, it obviously cannot be both nested and not nested. The only logical conclusion is that the class itself isn't nested.

嵌套类的定义特征是方法查找沿两个维度进行:在继承链中向上,并在嵌套中向外进行. Ruby与所有OO语言的99.9%一样,仅支持前一种. (从某种意义上说,嵌套类不仅继承其超类的功能,而且还继承其周围类的功能.)

The defining feature of nested classes is that method lookup goes along two dimensions: up the inheritance chain, and outwards through the nesting. Ruby, like 99.9% of all OO languages, only supports the former. (In some sense, nested classes inherit not only the features of their superclass, but also the features of their surrounding class.)

这篇关于嵌套类如何在Ruby中访问外部类中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆