From: Olivier Renaud Date: 2007-03-04T00:26:21+09:00 Subject: Re: define a function inside a method Le samedi 03 mars 2007 16:10, Robert Klemme a �crit�: > On 03.03.2007 15:41, Olivier Renaud wrote: > > Hi, > > > > I wrote a method which uses recursion, internally. As a test, I tried to > > define the recursive function inside the method that is called : > > > > class Ga > > def bu > > def zo(n) > > # recursively call zo > > end > > 10.times {|n| zo(n)} > > end > > > > At my surprise, this code ran well ! But I wonder if this is a good > > idea... Should I be aware of possible problems, or limitations, coming > > from this kind of construction ? I can't figure out where the zo function > > actually "lives". > > The issue here is (apart from the missing "end" in your piece above) > that zo will be defined every time you execute bu - that's probably not > something you want as it is inefficient and you do not actually change > zu's definition. Also, zo becomes a normal method - there is no such > thing as a nested method in Ruby: > > irb(main):001:0> class Ga > irb(main):002:1> def bu > irb(main):003:2> def zo(n) > irb(main):004:3> # recursively call zo > irb(main):005:3* end > irb(main):006:2> 10.times {|n| zo(n)} > irb(main):007:2> end > irb(main):008:1> end > => nil > irb(main):009:0> Ga.new.zo 1 > NoMethodError: undefined method `zo' for # > from (irb):9 > from :0 > irb(main):010:0> Ga.new.bu > => 10 > irb(main):011:0> Ga.new.zo 1 > => nil > > Kind regards > > robert Thanks, this is perfectly clear ! Finally, I rewrote this method to avoid the recursion, since it was a tail recursion. -- Olivier Renaud