From: Sean O'Dell Date: 2003-07-18T03:39:04+09:00 Subject: Re: What's the point? "Chad Fowler" wrote in message news:Pine.LNX.4.44.0307171413400.21595-100000@ns1.chadfowler.com... > On Fri, 18 Jul 2003, Brian Candler wrote: > > > On Fri, Jul 18, 2003 at 02:17:42AM +0900, Phil Tomson wrote: > > > As to your other question about "why?" - Sometimes I used to do this in > > > Perl to localize some functionality within a method (..errr, function or > > > subroutine in Perl parlance). Usually this was in a sort of refactoring > > > stage where I'd look at my sub and find that I had some duplicated code in > > > it that I could collect into another sub-sub. > > > > Beware, thar be demons. > > > > sub foo { > > my $x = $_[0]; > > sub bar { > > print "x is $x\n"; > > } > > bar(); > > } > > > > In Ruby, the equivalent code seems to fail, with local variables not being > accessible in nested methods. For example: > > irb(main):018:0> def go > irb(main):019:1> 1.upto(10) do |num| > irb(main):020:2* def my_meth > irb(main):021:3> puts "Printing #{num}" > irb(main):022:3> end > irb(main):023:2> end > irb(main):024:1> end > nil > irb(main):025:0> go > 1 > irb(main):026:0> my_meth > NameError: undefined local variable or method `num' for > # > from (irb):21:in `my_meth' > from (irb):26 > from ?:0 > > This seems unintuitive to me. I would expect variables declared in a > parent method to be accessible in child methods. Can someone tell me why > I'm wrong? I'm sure I am. :) Imagine the local function "my_meth" is defined outside of "go." The variable "num" wouldn't be accessible there, either. I think "my_meth" is thought of as a proc which just happens to be defined within "go" and not really local to "go." So, "my_meth" is not truly a local function then, I think. Sean O'Dell