2007/8/30, grocery_stocker <cdalten / gmail.com>:
> How come when I do something like
>
> #!/usr/bin/ruby -w
>
> def n_times(thing)
>         return thing
> end
>
> pi = n_times(23);
> puts pi
>
>
> the variable 'thing' doesn't go out of scope.
>
> But when I do something like
>
> #!/usr/bin/ruby
>
> def n_times(thing)
>         return lambda{|n| thing * n}
> end
>
> pi = n_times(23);
> puts pi.call(2)
>
>
> The varialble 'thing' does go out of scope.

Does it?

$ ruby<<XXX
> def n_times(thing)
>        return lambda{|n| thing * n}
> end
>
> pi = n_times(23);
> puts pi.call(2)
> puts thing
> XXX
46
-:7: undefined local variable or method `thing' for main:Object (NameError)

Ruby has static scoping rules but, err, can't remember the proper
term, dynamic binding.  When you create the lambda you create a
closure which keeps references in its environment alive.

Kind regards

robert