更新:由于这个答案最近似乎引起了一些兴趣,我想指出有discussion on the Ruby issue tracker to remove the feature discussed here, namely to forbid having method definitions inside a method body个.
不,Ruby没有嵌套的方法.
你可以这样做:
class Test1
def meth1
def meth2
puts "Yay"
end
meth2
end
end
Test1.new.meth1
但这是一种嵌套方法.我重复一遍:Ruby does not have嵌套方法.
这是一个动态的方法定义.当您运行meth1
时,meth1
的主体将被执行.正文恰好定义了一个名为meth2
的方法,这就是为什么在运行meth1
次之后,可以调用meth2
.
但meth2
的定义在哪里?很明显,它被定义为嵌套方法,因为Ruby中有are no个嵌套方法.它被定义为Test1
的一个实例方法:
Test1.new.meth2
# Yay
此外,每次运行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 does not支持嵌套方法.
还要注意,在Ruby中,方法体不能是闭包,只有块体可以.这几乎消除了嵌套方法的主要用例,因为即使if个Ruby支持的嵌套方法,也不能在嵌套方法中使用外部方法的变量.
更新继续:那么,在later个阶段,这个语法可能会被重新用于向Ruby添加嵌套方法,其行为方式与我描述的相同:它们将被限定在其包含方法的范围内,即在其包含方法体之外是不可见和不可访问的.而且,它们可能可以访问其包含方法的词法范围.然而,如果你阅读了我上面链接的讨论,你会发现matz非常反对嵌套方法(但仍然支持删除嵌套方法定义).