From: Brian Candler Date: 2011-04-27T00:28:00+09:00 Subject: Re: Setting a 'reference' inside the method body Xavier Noria wrote in post #995127: > On Tue, Apr 26, 2011 at 4:55 PM, Peter Szinek > wrote: > >> inside foo() we know whether we want to empty the array or not... it >> would be complicated to return something from foo() with the current >> architecture (based on which we could empty the hash or not). > > You cannot change the reference stored in the caller's baz, because > Ruby has pass by value semantics. But hashes are mutable, in > particular > > baz.clear > > wipes the hash, so the caller will see it empty as well. (bar.clear that is). Using bar.replace({}) is another option. Both of these mutate the Hash that was passed in. In Ruby: - all values are object references - all method calls are pass-by-value - a local variable is *not* itself an object - you cannot take a "reference" to a local variable Almost certainly you want to mutate the Hash being passed in, not attempt to modify the caller's local variable which holds the reference to that Hash. That said, there is one nasty way to achieve specifically what you asked: def bar(b) eval "baz='whoopee'", b end baz = {:fluff => :ork} bar(binding) p baz It involves either passing a Binding (as shown), or passing a block, which also carries a Binding, and then evaluating code in the context of that Binding. Unless you're writing a debugger or something like that, you almost certainly don't want to do this. -- Posted via http://www.ruby-forum.com/.