是否可以在方法中包含方法? [英] Is it possible to have Methods inside Methods?

查看:30
本文介绍了是否可以在方法中包含方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个方法中有一个方法.内部方法取决于正在运行的变量循环.这是个坏主意吗?

I have a method inside of a method. The interior method depends on a variable loop that is being run. Is that a bad idea?

推荐答案

UPDATE:由于这个答案最近似乎引起了一些兴趣,我想指出 讨论 Ruby 问题跟踪器以删除此处讨论的功能,即禁止在方法体.

UPDATE: Since this answer seems to have gotten some interest lately, I wanted to point out that there is discussion on the Ruby issue tracker to remove the feature discussed here, namely to forbid having method definitions inside a method body.

不,Ruby 没有嵌套方法.

No, Ruby doesn't have nested methods.

你可以这样做:

class Test1
  def meth1
    def meth2
      puts "Yay"
    end
    meth2
  end
end

Test1.new.meth1

但这不是一个嵌套方法.我再说一遍:Ruby 没有嵌套方法.

But that is not a nested method. I repeat: Ruby does not have nested methods.

这是什么,是一个动态方法定义.当您运行 meth1 时,将执行 meth1 的主体.body正好定义了一个名为meth2的方法,这就是为什么在运行一次meth1后,你可以调用meth2.

What this is, is a dynamic method definition. When you run meth1, the body of meth1 will be executed. The body just happens to define a method named meth2, which is why after running meth1 once, you can call meth2.

但是 meth2 在哪里定义的?嗯,显然没有定义为嵌套方法,因为在Ruby中没有嵌套方法.它被定义为Test1的一个实例方法:

But where is meth2 defined? Well, it's obviously not defined as a nested method, since there are no nested methods in Ruby. It's defined as an instance method of Test1:

Test1.new.meth2
# Yay

另外,很明显每次运行meth1都会重新定义:

Also, it will obviously be redefined every time you run meth1:

Test1.new.meth1
# Yay

Test1.new.meth1
# test1.rb:3: warning: method redefined; discarding old meth2
# test1.rb:3: warning: previous definition of meth2 was here
# Yay

简而言之:不,Ruby支持嵌套方法.

In short: no, Ruby does not support nested methods.

还要注意,在 Ruby 中,方法体不能是闭包,只有块体可以.这几乎消除了嵌套方法的主要用例,因为即使 Ruby 支持嵌套方法,您也不能在嵌套方法中使用外部方法的变量.

Note also that in Ruby, method bodies cannot be closures, only block bodies can. This pretty much eliminates the major use case for nested methods, since even if Ruby supported nested methods, you couldn't use the outer method's variables in the nested method.

UPDATE CONTINUED:在稍后阶段,此语法可能会被重新用于向 Ruby 添加嵌套方法,这将按照我描述的方式运行:它们的范围将限定为它们的包含方法,即在其包含的方法主体之外不可见和不可访问.并且可能,他们可以访问其包含方法的词法范围.但是,如果您阅读了我上面链接的讨论,您会发现 matz 严重反对嵌套方法(但仍然删除嵌套方法定义).

UPDATE CONTINUED: at a later stage, then, this syntax might be re-used for adding nested methods to Ruby, which would behave the way I described: they would be scoped to their containing method, i.e. invisible and inaccessible outside of their containing method body. And possibly, they would have access to their containing method's lexical scope. However, if you read the discussion I linked above, you can observe that matz is heavily against nested methods (but still for removing nested method definitions).

这篇关于是否可以在方法中包含方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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