方法内部是否可以有方法? [英] Is it possible to have Methods inside Methods?

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

问题描述

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

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: 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的主体.主体恰好定义了一个名为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在哪里定义?好吧,显然 not 没有定义为嵌套方法,因为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中,方法主体不能是闭包,只有块主体可以.这几乎消除了嵌套方法的主要用例,因为即使 if 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.

更新继续:在稍后阶段,然后,可以将该语法重新用于向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天全站免登陆