从类内部访问外部方法 [英] Access outer method from inside class

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

问题描述

有没有办法从类内部访问外部方法?例如:

Is there any way to access an outer method from inside a class? For example:

使用 .haml 文件(因此在 class Haml::Engine 中),定义一个 class Tumblr,并使用方法 self.render>.在Tumblr 类之外,#haml_concat 功能完美,但在Tumblr 内返回一个NameError.#haml_concatHaml::Helpers 中定义.为什么 #haml_concatTumblr 中无法使用?

Using a .haml file ( therefore inside class Haml::Engine), have a class Tumblr defined, with a method self.render. Outside of the Tumblr class, #haml_concat functions perfectly, but returns a NameError inside Tumblr. #haml_concat is defined in Haml::Helpers. Why is #haml_concat unusable inside Tumblr?

<打击>

value = 42

class TestClass
  def test_method
    value
  end
end

TestClass.new.value
# should ideally return 42

现在这只是返回 NameError: undefined local variable or method 'value' for #<TestClass:0x00000000e24960>.

推荐答案

如果你没有指定方法的接收者,ruby 会在当前对象的类中查找它,直到它的所有祖先.

If you don't specify receiver of the method, ruby looking it in the class of the current object and up to all its ancestors.

所以,因为Haml::Engine 不在Tumblr 祖先列表中,ruby 找不到这个方法.解决方案是指定您显式调用方法的对象.

So, because Haml::Engine is not in the list of Tumblr ancestors, ruby can't find this method. The solution is to specify object on which you calling method explicitly.

而且,你真的在​​ haml 文件中定义了 Tumblr 类吗?这看起来是一个非常糟糕的方法.

And, do you really define Tumblr class inside haml file? It looks like a very bad approach.

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

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