Robert Klemme
2/28/2006 1:37:00 PM
Godspeed wrote:
> Consider...
>
> def fred
> yield $k
> puts "in fred #{$k}"
> end
>
> $k=2
> fred {|o| o = 3}
> puts "outside fred #{$k}"
>
> produces:
>
> in fred 2
> outside fred 2
>
> why is $k still 2 after the call to fred?
Because Ruby does call by value where values are object references. Same
holds for blocks and their parameters. There is no implicit aliasing
between k$ and o. When the block is invoked you get a new reference which
initially points to the same instance as $k. Then you assign it and it
points to some other object leaving $k still pointing to the old instance.
Kind regards
robert